我正在使用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);
};
为什么将
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
的词法值)。