Reputation: 15695
function Person() {}
Person.prototype.population = 0;
Person.prototype.constructor = function(name) {
this.name = name;
console.log("Name: " + this.name);
console.log("Population: " + (++this.population) );
}
var p = new Person("Wex");
The following code doesn't seem to work, although logically I feel like it seems sound. How come this doesn't display the name and population?
Upvotes: 0
Views: 578
Reputation: 4109
Try this:
function Person() {}
Person.staticProperty = "foo";
var obj = new Person();
staticProperty is defined in Person object, which is the function.
Upvotes: 0
Reputation: 254924
http://jsfiddle.net/zerkms/gvjEF/
var Person = function(name) {
this.name = name;
console.log("Name: " + this.name);
console.log("Population: " + (++Person.population) );
};
Person.population = 0;
var p = new Person("Wex");
var p = new Person("Wex");
As long as you want static class variable you need:
classname.varname
this
Upvotes: 3