Sub topic 15
Closures, this, and Arrow Functions
This chapter assumes you know how closures capture variables from outer scopes, and that you have used this inside object methods. It explains why this often breaks inside callbacks and how arrow functions fix that through lexical scope.
Why `this` Is Not Captured Like a Variable
A closure captures the variables in its lexical environment. this is not an ordinary variable. A regular function gets its own this each time it is called, and the value depends on how the function is called, not where it was written.
So a regular function nested inside a method does not see the method's this. It gets a new this of its own, set by whoever calls it.
const timer = {
seconds: 0,
startBroken() {
setTimeout(function () {
// setTimeout calls this function, so `this` is not timer
console.log('broken:', this === timer); // broken: false
}, 0);
}
};
timer.startBroken();The callback was written inside startBroken, but setTimeout calls it later as a plain function. Its this is the global object in a browser, or a Timeout object in Node. In neither case is it timer.
The Old Fix: Capture `this` in a Variable
this is not captured, but ordinary variables are. Before ES2015, developers copied this into a variable so the closure could hold onto it:
const timer = {
seconds: 0,
start() {
const self = this; // ordinary variable, captured by the closure
setTimeout(function () {
self.seconds += 1;
console.log('self:', self.seconds); // self: 1
}, 0);
}
};
timer.start();The Modern Fix: Arrow Functions
An arrow function has no this of its own. When it reads this, JavaScript looks it up through the scope chain, just like a variable. The arrow function closes over the this of the function that encloses it.
function Timer() {
this.seconds = 0;
const id = setInterval(() => {
this.seconds += 1; // `this` comes from Timer's scope
console.log('tick:', this.seconds);
if (this.seconds === 3) clearInterval(id);
}, 100);
}
new Timer(); // tick: 1, tick: 2, tick: 3The self = this trick is the same idea. The arrow function just does it for you.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| Regular function as a callback inside a method | `this` is not the object | Use an arrow function |
| Arrow function as an object method | `this` comes from the outer scope, not the object | Use method syntax: `greet() {}` |
| Calling `.bind()` or `.call()` on an arrow | It has no effect on `this` | Use a regular function if you need to rebind |
The second mistake goes the other way from the first:
const user = {
name: 'Ada',
arrowCheck: () => this === user,
methodCheck() {
return this === user;
}
};
console.log(user.arrowCheck()); // false
console.log(user.methodCheck()); // trueExercise
Inside a method, [1, 2].forEach(function (n) { this.total += n; }) does not update the object's total. Why, and what is the smallest fix?
Show answer
The regular function gets its own this, which forEach sets to undefined (or the global object in sloppy mode), so it never refers to the object. Change the callback to an arrow function, (n) => { this.total += n; }. The arrow then uses the method's this from the enclosing scope.