【发布时间】:2020-06-02 00:59:32
【问题描述】:
我正在阅读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);
};
【问题讨论】:
标签: javascript ecmascript-6 ecmascript-5 arrow-functions