如何在JavaScript中实现类变量功能?

时间:2017-01-07 06:58:39

标签: javascript

我想跟踪使用构造函数创建了多少个对象。目前我通过在全局命名空间中放置humanCount变量来获取数字。但是,它对我来说并不好看。我的代码是:

var humanCount = 0;

function Human(name, age){
    this.name = name;
    this.age = age;
    humanCount++;
};

var john = new Human("JOHN", 35);
console.log(humanCount); // prints 1 

var jane = new Human("JANE", 28);
console.log(humanCount);  // prints 2

实现功能的任何其他方式?

2 个答案:

答案 0 :(得分:2)

你可以使计数器成为“类”(构造函数)的属性:

function Human(name, age){
    this.name = name;
    this.age = age;
    Human.count++;
};

Human.count = 0;

或者你可以把它变成原型的属性:

function Human(name, age){
    this.name = name;
    this.age = age;
    Human.prototype.count++;
};

Human.prototype.count = 0;

答案 1 :(得分:1)

创建humanCount属性,如:

function Human(name, age){
    this.name = name;
    this.age = age;
    Human.humanCount = (Human.humanCount || 0) + 1;
};