The previous lesson in this module covered getters, setters, and methods, and this one builds on that by looking at the single rule that causes the most confusion in JavaScript objects. The this binding is decided by the call site, which is the exact way that a function is invoked, and it is not decided by where the function was written or by what it happens to be a method of. That single rule explains every confusing this bug that you will meet, because the method works perfectly well until somebody passes it to a callback, and then it quietly starts pointing at something else entirely. This lesson walks through the rules that decide this, shows the three ways to take control of it, and ends with the practical order of preference for fixing a broken method. The last lesson in the module then looks at inheritance.
Why does this change when a method is passed around?
Here is a method that works when you call it normally, and that breaks the moment you pull it off the object.
class Stopwatch {
constructor(label) {
this.label = label;
this.elapsed = 0;
}
report() {
return this.label + ": " + this.elapsed + "s";
}
}
const watch = new Stopwatch("focus");
console.log(watch.report());
const detached = watch.report;
try {
detached();
} catch (err) {
console.log(err.constructor.name + ": " + err.message);
}
Calling watch.report() prints focus: 0s. Assigning the method to a variable and calling it there throws a TypeError that reads Cannot read properties of undefined (reading 'label'). Nothing about the function changed, because only the call changed. The first call had a receiver, which was watch, and the second call had no receiver at all, so this is undefined inside a class body, because class bodies are always strict.
This is worth separating from a related mistake. If report had been an ordinary function inside an object literal in loose code, then calling it detached would not have thrown. this would have silently become the global object, and the bug would have surfaced much later as a corrupted piece of unrelated data. Strict mode turns a silent corruption into a loud error, and that is one of the better arguments in favour of it.
What are the rules that decide this?
There are four of them, and they are tried in a fixed order. The first one that applies is the one that wins.
| How the function is called | What this is |
|---|---|
fn() with no receiver | undefined in strict mode, and the global object in loose mode |
obj.fn() | obj |
fn.call(x) or fn.apply(x) | x |
new Fn() | The fresh object that the constructor created |
| An arrow function | Whatever this was at the place where the arrow was created |
The first four of them are worth checking in a console, because seeing them behave differently is the fastest way to make the table stick in your mind.
"use strict";
function whoAmI() {
return this;
}
console.log(whoAmI());
const watch = { label: "focus", whoAmI };
console.log(watch.whoAmI() === watch);
console.log(whoAmI.call(watch) === watch);
console.log(whoAmI.apply(watch) === watch);
The first line prints undefined, because a plain function that is called with no receiver gets no this at all in strict mode. The next three lines all print true, because the method form, call, and apply all end up with watch as their this.
The arrow function row is the exception, and it is the one that saves the day most often. An arrow function has no this of its own at all, because it closes over the this of the scope where it was created. That is why this inside an arrow function can never be undefined, and why it can never be rebound with call, apply, or bind.
What do call, apply and bind actually do?
All three of them let you supply a receiver explicitly. call takes the receiver followed by the arguments. apply takes the receiver followed by an array of arguments. bind takes only the receiver, and it returns a new function with that receiver already attached.
class Stopwatch {
constructor(label) {
this.label = label;
this.elapsed = 0;
}
tick(seconds) {
this.elapsed += seconds;
return this.label + " at " + this.elapsed + "s";
}
}
const watch = new Stopwatch("focus");
const tick = watch.tick;
console.log(tick.call(watch, 5));
console.log(tick.apply(watch, [10]));
const boundTick = tick.bind(watch);
console.log(boundTick(15));
console.log(boundTick.name);
console.log(boundTick === tick);
The three calls print focus at 5s, focus at 15s, and focus at 30s, because they all add to the same elapsed time on the same watch. bind returns a brand new function, and the last line prints false to show that. The new function carries the name bound tick, which is a small but useful clue when you are reading a stack trace.
call and apply change the receiver for one call and then let it go. bind changes it permanently. When you want a method to survive being handed to a callback, bind is the one that you want.
Why do arrow functions fix the problem so neatly?
Because an arrow function copies the this of its surrounding scope at the moment that it is created. Declare it inside a method and it carries that method's this with it forever, no matter where it is called later on.
class Stopwatch {
label = "stopwatch";
elapsed = 0;
constructor(label) {
this.label = label;
}
tick = () => {
this.elapsed += 1;
return this.label + " at " + this.elapsed + "s";
};
}
const watch = new Stopwatch("focus");
const detached = watch.tick;
console.log(detached());
console.log(detached());
console.log(watch.elapsed);
Detaching the method no longer breaks anything. The two calls print focus at 1s and focus at 2s, because both of the arrows carry the this of the watch, and watch.elapsed ends up at 2, which shows that the state really did change on the original object.
The cost of this is that the arrow is a per-instance property rather than something shared on the prototype. Every stopwatch gets its own copy of the function, and because it is an own property it also shows up when you enumerate the keys of the object. For a handful of instances that is irrelevant, but for ten thousand of them it means ten thousand functions instead of one.
Why does a method lose this inside a callback?
Because every callback API calls your function without a receiver. map, forEach, setTimeout, and event listeners all invoke their callback with the arguments that they want and with nothing else, so this inside your method falls back to the rule about having no receiver.
class Playlist {
constructor(name) {
this.name = name;
}
format(track) {
return this.name + ": " + track;
}
}
const playlist = new Playlist("focus");
const tracks = ["alpha", "beta"];
try {
console.log(tracks.map(playlist.format));
} catch (err) {
console.log(err.constructor.name + ": " + err.message);
}
console.log(tracks.map(function (track) { return playlist.format(track); }));
console.log(tracks.map(playlist.format.bind(playlist)));
Passing the method straight into map throws a TypeError that reads Cannot read properties of undefined (reading 'name'), because map calls it with no receiver. Wrapping it in a function works and prints an array that holds the two strings focus: alpha and focus: beta. Binding it works as well and prints the same array.
One more trap hides here. Array callbacks receive three arguments, which are the element, the index, and the whole array. If your method takes a second parameter, then playlist.format used as a callback will receive the index where you expected your own argument. That is why the wrapper in the example above is usually the safer fix, because it forwards exactly the arguments that you choose.
What about timers and event handlers?
They are the same problem wearing different clothes. A timer or a listener stores your function and calls it later, with no receiver and with no interest at all in your object.
class Poller {
constructor(url) {
this.url = url;
this.attempts = 0;
}
poll() {
this.attempts += 1;
console.log("attempt " + this.attempts + " for " + this.url);
}
}
const poller = new Poller("/api/status");
setTimeout(poller.poll.bind(poller), 0);
setTimeout(function () { poller.poll(); }, 0);
Both timers fire and both of them print attempt 1 for /api/status and attempt 2 for /api/status, because both managed to keep this pointing at the poller. Handing poller.poll to setTimeout directly would have failed with the same TypeError that you saw with map.
For DOM event listeners the wrapper is the usual pattern, because the listener receives an event object that you want to pass on to a real method.
In what order should you reach for a fix?
- First, check whether the method needs
thisat all. A pure function that takes everything as arguments has no binding problem to solve. - Then use an arrow class field when the method is a callback that you hand to other code, because it is the smallest change and it cannot be unbound by accident.
- Use
bindwhen you need to keep the method as a shared prototype method, or when you are attaching a prototype method to an event listener. - Use
callandapplyonly when you genuinely want to swap the receiver for a single call, because they are a tool for borrowing behaviour and not a repair kit. - Never reach for
thisas an argument, in the style offunction (self) { self.x }. It works, but arrow functions andbindsay the same thing much more clearly.
Try it yourself: build a class Form with a constructor that stores this.fields = [], a method addField(name) that pushes onto that array, and a method render() that returns the field names joined with commas. Now write const names = ["email", "password"]; and try names.forEach(form.addField);. It will throw, because forEach calls your method without a receiver. Fix it in three different ways: wrap the call in a function, bind the method to the form, and convert the method into an arrow class field. Then check that form.fields.length is 2 after each version, and look at Object.keys(form) to see which of the fixes added an own property. Finally, write const r = form.render; and observe that it throws for the same reason that map did, because a method that reads this always needs a receiver.