【问题标题】:Static/shared property and method in JavaScriptJavaScript 中的静态/共享属性和方法
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 所以在我的帖子中我说var instanceNumber = myNamespace.myClass.getNextInstanceNo() - 它实际上试图做什么却没有做到,为什么?
猜你喜欢
  • 2013-12-20
  • 1970-01-01
  • 2013-03-28
  • 1970-01-01
  • 2014-02-18
  • 1970-01-01
  • 2015-11-03
  • 2011-03-24
  • 2012-03-30
相关资源
最近更新 更多