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?

  • 1
    Sure, have you tried it? – Bergi Jul 01 '13 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".) – Pointy Jul 01 '13 at 13:53
  • 1
    Please use the search function on stackoverflow first, i think this is the answer on your question: http://stackoverflow.com/a/1535687/863641 – Bjorn Jul 01 '13 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.) – JAB Jul 01 '13 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. – Pointy Jul 01 '13 at 14:04

2 Answers2

7

Sure, just add Person.personsCount without the prototype

Shlomi Schwartz
  • 8,693
  • 29
  • 109
  • 186
4

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

function Person() {
    Person.count++;
}
Person.count = 0;
Bergi
  • 630,263
  • 148
  • 957
  • 1,375