绑定它或使用变量更好吗? [英] Is it better to bind this or use a variable?

查看:69
本文介绍了绑定它或使用变量更好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

做得更好,

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆