好的,所以我想在 javascript 中创建一个构造函数,它将计算使用此构造函数创建的实例的总数。
var Component = function(name) {
this.name = name;
this.add = function(){this.prototype.countInstances++;};
this.add();
};
和
Component.prototype.countInstances=0;
按照我的正确理解,countInstances 变量被添加到原型(prototype)中,它将充当所有实例的静态副本,并将充当我的计数器。
此代码的问题在于,由于我在构造函数之后声明了 countInstances,因此构造函数代码本身出现了错误。如何纠正这个问题??
最佳答案
如果您希望将属性附加到类本身,而不是类的实例,则不希望将该属性添加到原型(prototype):
var Component = function(name) {
this.name = name;
Component.instanceCount++;
};
Component.instanceCount = 0;
这样,您将每个名称分配给它的实例,并将总实例计数分配给静态类:
var foo = new Component('bar');
var baz = new Component('qux');
console.info(foo.name, baz.name, Component.instanceCount);
>> 'bar', 'qux', 2
关于Javascript构造函数来计算实例数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30659822/