I was going through this article and couldn't understand their solution 1 to losing context:
let user = {
firstName: "John",
sayHi() {
alert(`Hello, ${this.firstName}!`);
}
};
// Problem:
setTimeout(user.sayHi, 1000); // Hello, undefined!
// Solution 1:
setTimeout(function() {
user.sayHi(); // Hello, John!
}, 1000);
In the second case, I understand that this works because the anonymous function callback gets access to a lexical environment populated with the globals (here, user
) but then even user.sayHi()
should have a similar lexical environment with access to the stuff between the surrounding {}
(i.e. firstName
) so we shouldn't need the wrapper in the first place. What am I missing here?