【发布时间】:2016-03-06 10:38:47
【问题描述】:
我理解(我认为)ES6 中的箭头函数使用Lexical this,但我不确定为什么一个由胖箭头函数调用的函数会将this 设置为未定义。
我需要做什么才能在handleAuthResult 中调用this.setResult?如果不需要,我不想使用旧的function () {}.bind(this)。
"use strict";
class Example {
constructor() {
this.checkAuth();
}
checkAuth() {
document.write("Checking auth now. ");
var iid = setInterval(() = > {
if (true) { // Have to do some dumb check here
clearInterval(iid);
this.authenticate(this.handleAuthResult)
}
}, 500);
}
authenticate(callback) {
callback({
value: true
});
}
handleAuthResult(result) {
document.write(`The result is ${result.value}.`);
this.setResult(result, this.loadThePage)
// ^ `this` is undefined here. How can I ever set the result?
}
// Another asynchronous thing
setResult(result, callback) {
callback();
}
loadThePage() {
document.write("The code never gets here, but the page should load now. ");
}
};
var example = new Example();
谢谢! https://jsfiddle.net/vujev4dj/
编辑: 在我为这被标记为重复的辩护中,我期望的行为确实在下面的小提琴中起作用,这就是我期望不必使用的原因ES6 中this.handleAuthResult 上的bind 函数:https://jsfiddle.net/m9e7j4ds/
【问题讨论】:
-
它在小提琴中起作用的原因是因为它使用
React.createClass()而不是使用ES6类(扩展React.Component)。React.createClass()绑定所有方法,使用 ES6 类时不会发生这种情况。 -
@bergi 我不同意这是您链接的问题的重复,因为它与将方法绑定到 ES6 类实例的方法无关。特别是,将箭头函数直接设为答案中未提及的类。我相信这就是提问者所要寻找的,尽管这个问题可以提出得更好。
标签: javascript scope ecmascript-6