ES6箭头函数与ES5:使用ES5非箭头函数时,如何知道将“ this”绑定到哪个函数

问题描述 投票:1回答:1

我正在使用ES6箭头功能阅读this article。它给出了以下示例,其中您必须使用bind(this),然后是带有箭头功能的相应代码。

var obj = {
  id: 42,
  counter: function counter() {
    setTimeout(function() {
      console.log(this.id);
    }.bind(this), 1000);
  }
};

它说In the ES5 example, .bind(this) is required to help pass the this context into the function

我想知道的事情:为什么在bind(this)的回调函数中使用setTimeout而不是counter函数?即为什么上面的代码不是这样的:

var obj = {
  id: 42,
  counter: function counter() {
    setTimeout(function() {
      console.log(this.id);
    }, 1000);
  }.bind(this);
};
javascript ecmascript-6 ecmascript-5 arrow-functions
1个回答
2
投票

为什么将bind(this)setTimeout的回调一起使用,而不是与计数器功能一起使用?

因为counter函数(其作用类似于obj对象的方法)已经具有正确的this,因为您像obj.counter()那样调用它,因此它通过将其称为this而获得了obj.counter()。假设您将计数器称为obj.counter(),然后在console.log(this.id)函数的第一行进行counter(),它将正确显示id值。

您传递给setTimeout()的回调没有自然的this值,除非您在回调函数本身上使用箭头函数或.bind(),因为当setTimeout()调用您的回调时,它不会设置特定的this值(它只是将回调作为常规函数调用),因此this值变为默认值。这意味着如果在this回调中以严格模式运行,则undefined将为setTimeout();如果在松散-鹅毛模式下运行,则为全局对象。

[调用函数时,请参阅设置this的值的6种方法。


我还应该提到,如果您做了这样的提议:

here

不仅完全不帮助var obj = { id: 42, counter: function counter() { setTimeout(function() { console.log(this.id); }, 1000); }.bind(this); }; 回调,而且还会将setTimeout()的错误值绑定到this方法。您会得到counter()定义之前的任何内容this(也称为var obj的词法值)。

© www.soinside.com 2019 - 2024. All rights reserved.