ES6 箭头函数 vs ES5:使用 ES5 非箭头函数时如何知道将 this 绑定到哪个函数
ES6 Arrow functions vs ES5: how to know which function to bind `this` to when using ES5 non-arrow function
我正在阅读 this article 关于使用 ES6 箭头函数的内容。它给出了以下示例,其中您必须使用 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);
};
Why do you use bind(this)
with the callback to setTimeout
rather than with the counter function?
因为 counter
函数(它的工作方式类似于 obj
对象的方法)已经有正确的 this
因为你像 obj.counter()
一样调用它所以它得到this
从称其为 obj.counter()
。假设您将计数器调用为 obj.counter()
,那么如果您在 counter()
函数的第一行执行 console.log(this.id)
,它将正确显示 id
值。
您传递给 setTimeout()
的回调没有自然的 this
值,除非您在回调函数本身上使用箭头函数或 .bind()
,因为当 setTimeout()
调用您的回调没有设置特定的 this
值(它只是将您的回调作为普通函数调用),因此 this
值变为默认值。这意味着 this
将是 undefined
如果 运行 严格模式或全局对象如果 运行 在 setTimeout()
回调内部的松散鹅模式。
查看调用函数时this
的值设置为here的6种方式
我还应该提一下,如果你按照你的建议做了这样的事情:
var obj = {
id: 42,
counter: function counter() {
setTimeout(function() {
console.log(this.id);
}, 1000);
}.bind(this);
};
它不仅对 setTimeout()
回调没有任何帮助,而且还会将 this
的错误值绑定到 counter()
方法。你会得到 var obj
定义之前的任何 this
(也称为 this
的词法值)。
我正在阅读 this article 关于使用 ES6 箭头函数的内容。它给出了以下示例,其中您必须使用 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);
};
Why do you use
bind(this)
with the callback tosetTimeout
rather than with the counter function?
因为 counter
函数(它的工作方式类似于 obj
对象的方法)已经有正确的 this
因为你像 obj.counter()
一样调用它所以它得到this
从称其为 obj.counter()
。假设您将计数器调用为 obj.counter()
,那么如果您在 counter()
函数的第一行执行 console.log(this.id)
,它将正确显示 id
值。
您传递给 setTimeout()
的回调没有自然的 this
值,除非您在回调函数本身上使用箭头函数或 .bind()
,因为当 setTimeout()
调用您的回调没有设置特定的 this
值(它只是将您的回调作为普通函数调用),因此 this
值变为默认值。这意味着 this
将是 undefined
如果 运行 严格模式或全局对象如果 运行 在 setTimeout()
回调内部的松散鹅模式。
查看调用函数时this
的值设置为here的6种方式
我还应该提一下,如果你按照你的建议做了这样的事情:
var obj = {
id: 42,
counter: function counter() {
setTimeout(function() {
console.log(this.id);
}, 1000);
}.bind(this);
};
它不仅对 setTimeout()
回调没有任何帮助,而且还会将 this
的错误值绑定到 counter()
方法。你会得到 var obj
定义之前的任何 this
(也称为 this
的词法值)。