假设我有一个旨在为以后添加一些回调的类。
function myclass() {
this.onSomething = function () {};
this.onOtherThing = function () {};
this.something = function () {
// stuff
this.onSomething();
};
this.otherThing = function () {
// other stuff
this.onOtherThing();
};
}
我不能拥有this.onSomething
和this.onOtherThing
存在,undefined
或者null
因为在something()
和中调用它们时otherThing()
会抛出错误,指出它们的类型不是函数。
由于需要那些空函数,但它们使用内存,因此如果这样做,该类的内存使用效率会更高吗?
function myclass() {
this.onSomething = empty;
this.onOtherThing = empty;
...
}
function empty() {
}
这样,每个类实例的属性都指向同一个空函数,而不是每次都创建新函数。我假设定义一个空方法不会占用很多内存,但是...从技术上来说这更好吗?
您为类的每个实例创建一个新函数这一事实是正确的。为了在所有实例之间共享它,您可以在类的原型上对其进行声明:
var MyClass = function() {
this.something = function () {
// stuff
this.onSomething();
};
this.otherThing = function () {
// other stuff
this.onOtherThing();
};
}
MyClass.prototype.onSomething = function() {};
MyClass.prototype.onOtherThing = function() {};
这样,所有实例将共享这些方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句