function Person(){
this.name = "Peter";
Person.counter++;
alert(Person.counter);
}
Person.counter = 0;
var p1 = new Person();
var p2 = new Person();
Make the "static" variable a property of the Person
function, rather than the prototype
, and use Person
instead of this
inside the constructor.
This is possible because JavaScript functions are first-class (i.e. they are objects), so can have properties of their own.
Here's a working example of the above code.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…