Losing this, and Getting It Back
A method separated from its object stops working, and this one bug accounts for a large share of the real confusion about this.
Pulling a method out of its object, passing it as a callback, or destructuring it all drop the object before the dot. The fixes are an arrow wrapper, bind, or a class field, and each suits a different situation.
EXERCISE
1The Three Ways a Method Gets Separated
They look different and they are the same bug: the object before the dot disappeared.
You met this briefly in lesson 1. Here it is properly, because it is the single most common this problem in real code and it arrives in three disguises.
Disguise one: assigning the method to a variable.
const user = {
name: "Ada",
greet() {
return `Hi, ${this.name}`;
},
};
const greet = user.greet;
console.log(greet()); // TypeError: Cannot read properties of undefined
Disguise two: passing the method as a callback.
const counter = {
count: 0,
increment() {
this.count += 1;
},
};
[1, 2, 3].forEach(counter.increment); // TypeError
setTimeout(counter.increment, 100); // TypeError
button.addEventListener("click", counter.increment); // same problem
Disguise three: destructuring it out.
const { greet } = user;
console.log(greet()); // TypeError, identical to disguise one
All three are the same thing. user.greet evaluates to the function, and the connection to user exists only in the expression user.greet(), at the moment of the call. Store the function anywhere, hand it to anything, and that connection is gone. Rule 3 no longer applies, so rule 4 does, and this is undefined.
Nothing is broken or copied, which is the part that makes it confusing:
const greet = user.greet;
console.log(greet === user.greet); // true, the identical function
Same function object. Only the call site changed.
And why the error message points at the wrong thing:
// TypeError: Cannot read properties of undefined (reading 'name')
It names name, so people go looking at the name property. The property is fine. this is undefined, and name is simply the first thing the code tried to read from it. Once you recognise that message shape, the real question is always "what happened to this here".
Pro Tip: Any time you write a method name without immediately calling it, you have separated it. That means
obj.methodpassed as a callback, assigned to a variable, or destructured. The moment you type it without the parentheses following, ask yourself whatthiswill be when someone else calls it, because you have just handed away the part that answered that question.
EXERCISE
2Three Fixes, and When Each One Fits
There is no single right answer, but there is a right answer for each situation, and they are easy to tell apart.
Fix one: wrap it in an arrow.
const counter = {
count: 0, increment() {
this.count += 1;
}
};
setTimeout(() => counter.increment(), 100);
[1, 2, 3].forEach(() => counter.increment());
The arrow is the callback, and inside it you write a normal method call with counter before the dot. Rule 3 applies again. This is the clearest fix and usually the one to reach for, because the call site reads exactly like the working version.
It also lets you control the arguments, which matters more than it sounds:
// Broken in a different way: forEach passes (item, index, array)
[10, 20, 30].forEach(console.log);
// 10 0 [10,20,30] <- three arguments, not one
[10, 20, 30].forEach((n) => console.log(n)); // 10 20 30
Fix two: bind it.
setTimeout(counter.increment.bind(counter), 100);
// Or bind once and reuse, which is common in constructors:
function Counter() {
this.count = 0;
this.increment = this.increment.bind(this);
}
Use bind when you need the function itself rather than a call, and especially when you must be able to remove it later:
// This cannot be removed, because a new arrow is created each time:
element.addEventListener("click", () => handler());
element.removeEventListener("click", () => handler()); // does nothing
// This can, because you hold the exact function that was added:
const bound = handler.bind(obj);
element.addEventListener("click", bound);
element.removeEventListener("click", bound); // works
Fix three: make it a class field that is already an arrow.
class Counter {
count = 0;
increment = () => {
this.count += 1;
};
}
const c = new Counter();
[1, 2, 3].forEach(c.increment);
console.log(c.count); // 3, no binding needed anywhere
increment is a property on each instance holding an arrow, and the arrow captured this from the constructor. It cannot be separated because it never depended on the call site. The cost is one function per instance rather than one shared on the prototype, which is the trade-off from Unit 1. Unit 3 covers class fields properly.
Pro Tip: Arrow wrapper when you want a call,
bindwhen you want a function you can hold on to and remove again, class field when a method will always be used as a callback. Pick by what you need to do with the result, and the choice makes itself.
EXERCISE
3Reading Real Code That Handles this
Once the fixes are familiar, several patterns that look like noise in real codebases turn out to be one of them.
You now have enough to read the this handling in most real code. Here are the shapes you will meet.
The constructor that binds everything up front:
class Toolbar {
constructor() {
this.items = [];
this.handleSave = this.handleSave.bind(this);
this.handleDelete = this.handleDelete.bind(this);
}
handleSave() {
console.log(this.items.length);
}
handleDelete() {
console.log("deleting");
}
}
This was the standard class-component pattern for years. The methods live on the prototype where they are shared, and the constructor replaces each one on the instance with a bound copy, so they can be passed as event handlers safely.
The self or that variable in older code:
function Timer() {
const self = this; // capture it while we still have it
this.seconds = 0;
setInterval(function () {
self.seconds += 1; // `this` is wrong in here; `self` is not
}, 1000);
}
Written before arrow functions existed. The variable is an ordinary closure capture, which was the only tool available. Seeing const self = this dates a file to pre-2015, and an arrow function replaces it exactly.
Methods that deliberately accept a this:
[1, 2, 3].forEach(function (n) {
console.log(this.prefix, n);
}, { prefix: ">" });
// > 1
// > 2
// > 3
forEach, map, filter and several others take an optional second argument used as this inside the callback. It predates arrows and you will rarely write it, but it explains an argument you might otherwise think was a mistake. Note it has no effect on an arrow callback, which has no this to set.
And the one that is simply a bug:
class Api {
base = "/v1";
get(path) {
return this.base + path;
}
}
const api = new Api();
const paths = ["/users", "/posts"].map(api.get);
// TypeError: Cannot read properties of undefined (reading 'base')
const ok = ["/users", "/posts"].map((p) => api.get(p));
console.log(ok); // [ '/v1/users', '/v1/posts' ]
Passing api.get straight into map separates it. The arrow wrapper fixes it, and by now you can see why without running it.
Pro Tip: When you open an unfamiliar file and see
.bind(this)in a constructor,const self = this, or arrows wrapping every callback, you are looking at three generations of the same fix for the same problem. None of them is wrong. Recognising which one a codebase uses tells you roughly when it was written and what to match when you add to it.
