绑定它或使用变量更好吗? [英] Is it better to bind this or use a variable?
问题描述
做得更好,
asset.addEventListener("load", function () {
this.emit({
type: "load",
asset: asset
});
}.bind(this), false);
或
var scope = this;
asset.addEventListener("load", function () {
scope.emit({
type: "load",
asset: asset
});
}, false);
绑定函数是否更好,或者只是将引用存储到这个
在变量中?
Is it better to bind the function, or just store the reference to this
in a variable?
推荐答案
我觉得第二种选择更好,只是为了防止任何混淆。使用这个
一直是许多JavaScript问题的问题,所以当你可以避免它时,你应该在我看来。顺便说一下,这也是在像Knockout这样的库中完成的。
I feel that the second option is better, just to prevent any confusion. The usage of this
has been the problem of many a JavaScript problem, so when you can avoid it you should in my opinion. By the way, this is also done in libraries like Knockout.
如果你想了解更多关于这个
关键字,这是对<* c $ c>这个的各种不同值的一个很好的解释: http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/
If you'd like to know more about the this
keyword, this is a nice explanation of the various different values this
can have in different contexts: http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/
这篇关于绑定它或使用变量更好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!