2

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?

5
  • 1
    Sure, have you tried it? Commented Jul 1, 2013 at 13:52
  • Yes, you can do that. (You don't really mean, "in a JavaScript object"; you mean, "in a class of JavaScript objects".) Commented Jul 1, 2013 at 13:53
  • 1
    Please use the search function on stackoverflow first, i think this is the answer on your question: stackoverflow.com/a/1535687/863641 Commented Jul 1, 2013 at 13:54
  • @Pointy classes are just objects in JavaScript anyway. (Though I don't think "class" is the right word to use in JavaScript to begin with, but I haven't used prototypes enough to know for sure.) Commented Jul 1, 2013 at 14:00
  • @JAB yes I agree; I meant "class" in the more generic, colloquial sense :) The point was that if you've only got one object, the concept of "static member" isn't really meaningful. Commented Jul 1, 2013 at 14:04

2 Answers 2

7

Sure, just add Person.personsCount without the prototype

Sign up to request clarification or add additional context in comments.

Comments

4

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

function Person() {
    Person.count++;
}
Person.count = 0;

Comments