是不是更好做,
asset.addEventListener("load", function () {
this.emit({
type: "load",
asset: asset
});
}.bind(this), false);
Or
var scope = this;
asset.addEventListener("load", function () {
scope.emit({
type: "load",
asset: asset
});
}, false);
绑定函数更好,还是只存储对函数的引用this
在变量中?
这实际上取决于很多因素。以下是一些注意事项:
另一种可以考虑的选择是让你的对象实现事件监听器界面。这将让您将对象本身作为处理程序传递,并将调用您的实现handleEvent()
您提供的方法。
然后this
value 将自动成为您的对象。
所以如果你的this
是一个来自构造函数的对象,你可以这样做:
function MyCtor() {
// your constructor
}
// This implements the `Event Listener` interface
MyCtor.prototype.handleEvent = function(event) {
// ------v----should be "load"
return this[event.type](event)
};
// This is the `load` handler
MyCtor.prototype.load = function(event) {
this.emit({
type: "load",
asset: event.currentTarget
});
};
然后像这样绑定处理程序:
asset.addEventListener("load", this, false);
现在你的价值this
句柄事件中将是您的对象,因此您可以调用它的其他方法,并且两者都不是.bind
也不需要闭包变量。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)