使用原型模拟静态变量

时间:2012-06-15 00:11:44

标签: javascript

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");

以下代码似乎不起作用,虽然逻辑上我觉得它似乎听起来像。为什么这不显示名称和人口?

2 个答案:

答案 0 :(得分:3)

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");

只要您需要静态类变量:

  1. 将其定义为classname.varname
  2. 使用类名来使用它,而不是this

答案 1 :(得分:0)

试试这个:

function Person() {}
Person.staticProperty = "foo";
var obj = new Person();

staticProperty在Person对象中定义,它是函数。