Wex
Wex

Reputation: 15695

Emulating static variables using prototype

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

Answers (2)

odiszapc
odiszapc

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

zerkms
zerkms

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:

  1. define it as classname.varname
  2. use it using the classname, not this

Upvotes: 3

Related Questions