【问题标题】:Why does storing a reference to a function then calling the function cause 'this' to have a context of window?为什么存储对函数的引用然后调用该函数会导致“this”具有窗口上下文?
【发布时间】:2013-02-14 16:07:58
【问题描述】:

我正在阅读 _.bind 和 _bindAll 的教程:http://blog.bigbinary.com/2011/08/18/understanding-bind-and-bindall-in-backbone.html

网站有如下代码

function Developer(skill) {
  this.skill = skill;
  this.says = function(){
    alert(this.skill + ' rocks!');
  }
}
var john = new Developer('Ruby');
john.says(); //Ruby rocks!

对

function Developer(skill) {
  this.skill = skill;
  this.says = function(){
    alert(this.skill + ' rocks!');
  }
}
var john = new Developer('Ruby');
var func = john.says;
func();// undefined rocks!

为什么存储对函数的引用然后调用该函数会导致 this 具有窗口上下文?

【问题讨论】:

  • 因为变量func的上下文是window对象,而不是john。你应该做var func = john.says.bind(john);

标签: javascript


【解决方案1】:

当你执行时

a.b();

那么a 是b 的执行上下文(this 在b 中),除非b 是一个绑定函数。

如果你没有a,那就是如果你有

b();

那么就和

一样了
window.b();

所以window 是b 的执行上下文。

还要注意

a.b();

与

相同
b.call(a);

和

b();

与

相同
b.call(); // call replaces its first argument by the global object if it's null or undefined

如果你想绑定上下文,那么你可以(在现代浏览器上)

var func = john.says.bind(john);
func();

或者(更经典的)使用闭包:

var func = function(){john.says()};
func();

【讨论】:

  • 我确信有人有理由拒绝我。我能开悟吗?
  • 这真的让我更清楚。谢谢。基本上你所说的是上下文是“点”之前的对象,如果没有“点”它是窗口
【解决方案2】:

因为“this”关键字是在调用时间绑定的,而不是定义时间。

当您拨打john.says() 时,就像拨打john.says.apply(john)。

当您拨打func() 时,就像拨打func.apply()。

Yehuda Katz 对“JavaScript function invocation and this”有很好的解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 2020-07-28
    • 1970-01-01
    相关资源
    最近更新 更多