假设我有一个类,旨在稍后添加一些回调。
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() {
}
这样每个类实例的属性都指向同一个空函数,而不是每次都创建新函数。我认为定义一个空方法不会占用大量内存,但仍然......这在技术上更好吗?
最佳答案
您的说法是正确的,即为类的每个实例创建一个新函数。为了在所有实例之间共享它,您可以在类的原型(prototype)上声明它:
var MyClass = function() {
this.something = function () {
// stuff
this.onSomething();
};
this.otherThing = function () {
// other stuff
this.onOtherThing();
};
}
MyClass.prototype.onSomething = function() {};
MyClass.prototype.onOtherThing = function() {};
这样,这些方法将被所有实例共享。
关于javascript - 使用通用的空函数而不是在每个类实例中创建一个新函数是否更有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40738915/