【发布时间】:2012-04-18 15:02:46
【问题描述】:
我正在尝试在 JS 中创建一个“类”来跟踪自身实例化了多少个实例。我正在尝试这样做......
var myNamespace = {};
myNamespace.myClass = function () {
//fails here as .getNetInstanceNo() not recognised...
var instanceNumber = myNamespace.myClass.getNextInstanceNo();
return {
instanceNo : function() { return instanceNumber; }
}
};
myNamespace.myClass.InstanceNo = 0; //static property?
//should the class itself have this method added to it...
myNamespace.myClass.prototype.getNextInstanceNo = function () { //static method?
return myNamespace.myClass.InstanceNo++;
};
var class1 = new myNamespace.myClass();
alert('class 1 has instance of ' + class1.instanceNo() );
但是,由于无法识别 getNextInstanceNo 函数,这会失败。即使我认为我是通过myClass.prototype 添加它。
我做错了什么?
【问题讨论】:
-
In 可以通过简单地不将方法添加到
.prototype来解决这个问题 - 但我认为这几乎就是原型的用途?!
标签: javascript class static-methods