Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating "static" members in a javascript object [duplicate]

Is there a way to create "static" members in a JS Object?

function Person(){

}

Person.prototype.age = null;
Person.prototype.gender = null;

I would like to add personsCount as a static member, is that possible?


2 Answers

Sure, just add Person.personsCount without the prototype

like image 79
Shlomi Schwartz Avatar answered Dec 15 '25 11:12

Shlomi Schwartz


Common practise is to make such "static members" properties of the constructor function itself:

function Person() {
    Person.count++;
}
Person.count = 0;
like image 44
Bergi Avatar answered Dec 15 '25 09:12

Bergi