let obj = {
name: "asim",
sayLater: function () {
console.log(this); // `this` points to obj
setTimeout(() => {
console.log(this); // `this` points to obj
console.log(`${this.name}`); // `this` points to obj
}, 1000);
}
};
obj.sayLater();
If we were to replicate the same behavior without the fat arrow function, we would need to store this to a separate variable (e.g. self) in the appropriate context first and then call the variable where this changes the calling context.
let obj = {
name: "asim",
sayLater: function () {
let self = this; // Assign to self
console.log(self);
console.log(this); // `this` points to obj
setTimeout(function () {
console.log(`${self.name}`); // Use self not this
}, 1000);
}
};
See: https://codecraft.tv/courses/angular/es6-typescript/arrow/ Fat arrow functions have a concise syntax and, most importantly, doesn't change the calling context for
this
.If we were to replicate the same behavior without the fat arrow function, we would need to store
this
to a separate variable (e.g.self
) in the appropriate context first and then call the variable wherethis
changes the calling context.