Chapter XXI · The `this` Keyword
Arrow Functions and `this`
Arrow functions do not have their own `this` binding; instead, they inherit `this` lexically from their enclosing scope.
01 How It Works
Think of a mirror reflecting the exact environment lighting of the room it sits inside.
Because arrow functions lack an execution context `this`, they look outward lexically to resolve references, solving traditional callback `this` loss issues.
const obj = {
name: "Alice",
delayedGreet: function() {
setTimeout(() => {
console.log(`Hi ${this.name}`); // Inherits 'this' from delayedGreet
}, 1000);
}
};
obj.delayedGreet();
1. Write an arrow function inside a parent method or scope.
2. Access `this` inside the arrow function body.
3. Observe lexical resolution pointing to the enclosing parent scope's `this`.
02 Practical Example
Here is how you might see this concept applied in real-world code:
const group = {
title: "Devs",
list: ["A", "B"],
showList() {
this.list.forEach(item => console.log(this.title + ": " + item));
}
};
group.showList();
Key Takeaway
Arrow functions lexically inherit `this`, preventing unexpected context loss in nested callbacks.