const counter = {
value: 42,
logAfterDelay() {
setTimeout(function() {
console.log(this && this.value);
}, 0);
},
};
counter.logAfterDelay();const counter = {
value: 42,
logAfterDelay() {
setTimeout(() => {
console.log(this.value);
}, 0);
},
};
counter.logAfterDelay();Bug: Regular function callbacks lose their this context. Inside the setTimeout, this is undefined — not counter.
Explanation: Arrow function callbacks inherit this from their enclosing scope — here, the logAfterDelay method where this is counter.
Key Insight: Use arrow functions as callbacks inside methods to preserve the outer this.