Since this
in arrow functions refers to lexical context, it is expected that the following code would log the object itself:
const arrow = () => {
console.log(this);
};
const object = {
render() {
setTimeout(arrow, 1000);
},
};
object.render();
However it actually logs the global
object. This is confusing to me because
when I use an inline arrow function, it works fine and logs the obj
:
const object = {
render() {
setTimeout(() => {
console.log(this);
}, 1000);
},
};
object.render();
With an inline version of the same arrow function the code logs the object itself, which is exactly what I want. I'm really confused about why this happens. They are both arrow functions, aren't they?
*Update: Thanks for the answers! So this
in arrow functions keeps the reference when they were defined. But what about this
in a class? e.g.,
class MyClass {
handleChange = () => {
console.log(this);
};
render() {
setTimeout(this.handleChange, 1000);
}
}
const myclass = new MyClass();
myclass.render();
In this case, this
in handleChange
refers to the object myclass
. But if it keeps the original reference, shouldn't it refers to the global
when it was defined?