Sub topic 10
Keeping this Bound When Methods Become Callbacks
This chapter assumes you know how to declare classes, instance methods, and public fields, and that you understand the basic rule that this is set by how a function is called. It covers why class methods lose this when you pass them around, and three ways to fix it.
Why the Method Forgets Its Instance
In JavaScript, this does not belong to a method. It is decided at each call, based on what sits to the left of the dot. A call like btn.describe() sets this to btn. If you copy the method into a variable, or pass it as a callback, the dot is gone. The function then runs with no receiver.
In sloppy-mode functions, a missing receiver falls back to the global object. Class bodies always run in strict mode, so a missing receiver leaves this as undefined. Reading this.label then throws a TypeError.
Seeing the Bug
The example below uses a small runLater helper that stands in for any API that takes a callback, such as an event emitter or an array method.
class Button {
label = 'OK';
handleClick = () => this.label;
describe() {
return this.label;
}
}
function runLater(callback) {
return callback(); // called with no receiver
}
const btn = new Button();
console.log(btn.describe()); // 'OK'
console.log(runLater(btn.handleClick)); // 'OK'
try {
runLater(btn.describe);
} catch (err) {
console.log(err instanceof TypeError); // true
}handleClick works because it is an arrow function stored in a field. Arrow functions have no this of their own. They capture this from the scope where they are created, and field initializers run with this set to the new instance.
Three Fixes
class Timer {
seconds = 0;
constructor() {
// Fix 2: bind once in the constructor
this.tickBound = this.tick.bind(this);
}
tick() {
this.seconds++;
return this.seconds;
}
// Fix 1: arrow function field
reset = () => {
this.seconds = 0;
return this.seconds;
};
}
const t = new Timer();
const call = (fn) => fn();
console.log(call(t.tickBound)); // 1
console.log(call(() => t.tick())); // 2 (Fix 3: wrap at the call site)
console.log(call(t.reset)); // 0| Fix | Where the function lives | Trade-off |
|---|---|---|
| Arrow field | On each instance | One function per instance. Subclasses can't call it with `super.reset()`. |
| `bind` in constructor | Prototype method plus a bound copy on the instance | Two names to keep track of, and the bound copy still costs memory per instance. |
| Wrap at call site | Prototype only | You have to remember it at every call site. |
Common Errors
- Passing
obj.methodtoaddEventListener,setTimeout, or.map()and expectingthisto follow it. - Destructuring methods:
const { save } = store;loses the receiver. - Turning every method into an arrow field "just in case". This breaks
supercalls and prototype sharing.
Exercise
A class Logger has a prototype method log() that reads this.prefix. The code calls items.forEach(logger.log) and throws a TypeError. Give two fixes that keep log() as a prototype method.
Show answer
Wrap it at the call site with items.forEach((x) => logger.log(x)), or pass the instance as forEach's second argument: items.forEach(logger.log, logger). A third option is to bind once in the constructor (this.log = this.log.bind(this)). This keeps the prototype method and adds a bound copy on the instance.
Exercise
Why does an arrow function stored in a class field see the instance as this, when an arrow function written directly in the class body as a method cannot exist?
Show answer
Field initializers run during construction with this set to the new instance, so an arrow created there captures that instance. Method definitions use their own method syntax and get this from the call, so the class body has no place to write an arrow as a method.