我想要一个班级'在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
添加它。
我做错了什么?
答案 0 :(得分:4)
prototype
是一个对象,其他对象从该对象继承属性,就像在创建对象的实例时那个对象没有属性/方法一样,在调用时,类的原型在其中搜索该属性/方法所属的对象,这是一个简单的例子:
function Animal(){};
Animal.prototype.Breathe = true;
var kitty= new Animal();
kitty.Breathe; // true (the prototype of kitty breathes)
var deadCat = new Animal();
deadCat.Breathe = false;
deadCat.Breathe; // false (the deadCat itself doesn't breath, even though the prototype does have breath
正如您自己所说,您不需要在原型上定义getNextInstanceNo,因为这不是在JavaScript上定义静态方法的方法,而是将其保留在类本身上,而是可以定义instanceNo
原型上的方法,方法如下:
var myNamespace = {};
myNamespace.myClass = function () {
this.instanceNumber = myNamespace.myClass.getNextInstanceNo();
};
myNamespace.myClass.prototype.instanceNo = function () {
return this.instanceNumber;
};
myNamespace.myClass.InstanceNo = 0;
myNamespace.myClass.getNextInstanceNo = function () {
return myNamespace.myClass.InstanceNo++;
};
var class1 = new myNamespace.myClass();
alert('class 1 has instance of ' + class1.instanceNo());