Mega Man Mega Man - 1 month ago 13
Javascript Question

JavaScript - this inside of timeout with arrow functions

Why isn't

this
inside of the
setTimeout
equal to the object that invoked the render function when using arrow functions?

class X {
constructor(config) {
this.data = config.data;
this.render_ = config.render;
}
render() {
this.render_(this.data);
}
}
var x = new X({
data: [1, 2, 3],
render: (data) => {
setTimeout(() => {
console.log(this);
}, 200);
}
});
x.render();

Answer

Read the part of the arrow function documentation that says "Arrow functions used as methods"

in summary: arrow functions just simply do not bind this or their own version of this, but rather references the global Window object.

Comments