I understand (I think) that arrow functions in ES6 use Lexical this, but I'm not sure why a function called by a fat arrow function would have this
set as undefined.
What do I have to do to be able to call this.setResult
in handleAuthResult
? I do not want to use the old function () {}.bind(this)
if I don't need to.
"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();
Thanks! https://jsfiddle.net/vujev4dj/
Edit: in my defense of this being marked as duplicate, the behaviour I expected does work in the following fiddle, which is why I expected to not have to use the bind
function on this.handleAuthResult
in ES6: https://jsfiddle.net/m9e7j4ds/