Sub topic 10
Keeping this Bound When Methods Become Callbacks
This chapter assumes you know how arrow functions differ from regular functions, how destructuring works, and how class methods and public instance fields are declared (covered in earlier chapters). It also assumes the basic rule that this inside a regular function depends on how the function is called. Here you will see why class methods lose their this when passed around, how to recognize the failure, and which of the common fixes suits a given situation.
Why Methods Lose this
A class method is an ordinary function stored on the class's prototype. It has no permanent link to any instance. The value of this inside it is decided at each call, by the expression used to call it:
obj.method()setsthistoobj.method()with no object in front setsthistoundefined, because class bodies always run in strict mode.method.call(x)ormethod.apply(x)setsthistox.
When you pass obj.method as an argument, you pass only the function. The obj. part is not passed along. Whoever calls the function later calls it plainly, and this becomes undefined.
class Button {
label = 'OK';
handleClick = () => this.label;
describe() {
return this.label;
}
}
const btn = new Button();
const { handleClick, describe } = btn;
console.log(handleClick()); // 'OK'
try {
describe();
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // e.g. "Cannot read properties of undefined (reading 'label')"
}Destructuring describe from btn detaches it, just like passing btn.describe to another function would. handleClick keeps working because it is an arrow function created inside the instance, and arrow functions take this from where they were defined.
Where Detachment Happens
You rarely destructure a method on purpose. Detachment usually happens when a method is handed to some API that calls it later.
| Situation | Example | Why this is lost |
|---|---|---|
| Timers | `setTimeout(obj.tick, 100)` | The timer calls the function plainly |
| DOM events | `el.addEventListener('click', obj.onClick)` | `this` becomes the element, not your object |
| Array callbacks | `items.map(obj.format)` | `map` calls the callback with `this` undefined |
| Promises | `fetchData().then(obj.handle)` | Promise reactions are plain calls |
| Storing a reference | `const fn = obj.save; fn()` | The receiver is dropped at assignment |
The DOM case is a trap of its own. Your method does not crash with undefined. It runs with this set to the element, so this.label silently reads a property of the element instead of your object.
The error message is your main clue. When you see "Cannot read properties of undefined" with a property name that belongs to your class, look for a place where a method was passed as a value.
Fix 1: Wrap the Call in an Arrow Function
The smallest fix happens at the call site. Pass a new arrow function that calls the method on the instance:
class Timer {
constructor() {
this.ticks = 0;
}
tick() {
this.ticks++;
console.log(`tick ${this.ticks}`);
}
}
const t = new Timer();
setTimeout(() => t.tick(), 10); // tick 1Inside the arrow, t.tick() is a normal method call, so this is t. The class stays unchanged. The downside is that every call site must remember to do this, and each wrapper is a new function. That matters for removeEventListener, covered below.
Fix 2: Bind in the Constructor
Function.prototype.bind returns a new function whose this is fixed. Doing it in the constructor stores a bound copy as an own property of each instance:
class Logger {
constructor(prefix) {
this.prefix = prefix;
this.log = this.log.bind(this);
}
log(message) {
console.log(`${this.prefix}: ${message}`);
}
}
const logger = new Logger('app');
['started', 'ready'].forEach(logger.log);
// app: started
// app: readyThe right-hand this.log finds the prototype method. The assignment then creates an own property named log on the instance, which shadows the prototype method. The original method stays on the prototype, so subclasses can override it and super.log() still works. In a subclass, this.log in the parent constructor already resolves to the subclass override, so the bound version is the override.
Fix 3: Arrow Function Fields
A public field that holds an arrow function is created once per instance, while the constructor runs. The arrow captures that instance as its this:
class Counter {
count = 0;
increment = () => {
this.count++;
return this.count;
};
}
const c = new Counter();
const inc = c.increment;
inc();
console.log(inc()); // 2This is short and popular in UI code, but it has costs you should know about.
Gotcha: Arrow Fields Are Not on the Prototype
An arrow field is an own property, not a method. As a result:
- Each instance gets its own function object, so memory grows with the number of instances.
super.increment()in a subclass finds nothing, becausesuperlooks on the parent's prototype.- Stubbing
Counter.prototype.incrementin tests has no effect.
Gotcha: Arrow Fields Shadow Subclass Methods
This is the one that causes real bugs. Parent fields are set on the instance during the parent constructor, and own properties win over anything on the prototype chain:
class Base {
greet = () => 'hello from Base';
}
class Child extends Base {
greet() {
return 'hello from Child';
}
}
console.log(new Child().greet()); // 'hello from Base'Child.prototype.greet exists, but the instance's own greet property hides it. If you expect subclasses to override a callback, define it as a method and bind it in the constructor instead.
Stable References and removeEventListener
removeEventListener only removes a listener if you pass the exact same function object you added. Inline arrows and inline bind calls create a new function every time, so this code never removes anything:
// Broken: each bind() returns a different function
// el.addEventListener('click', this.onClick.bind(this));
// el.removeEventListener('click', this.onClick.bind(this));Binding in the constructor or using an arrow field gives you one stable function per instance. You can add and remove it reliably. The following example uses Node's EventTarget, which works the same way as the DOM version:
class Widget {
clicks = 0;
constructor(target) {
this.target = target;
this.onClick = this.onClick.bind(this);
target.addEventListener('click', this.onClick);
}
onClick() {
this.clicks++;
}
destroy() {
this.target.removeEventListener('click', this.onClick);
}
}
const target = new EventTarget();
const w = new Widget(target);
target.dispatchEvent(new Event('click'));
w.destroy();
target.dispatchEvent(new Event('click'));
console.log(w.clicks); // 1Other Tools Worth Knowing
Some array methods accept a thisArg as their second argument: forEach, map, filter, some, every, find, and findIndex. items.map(obj.format, obj) works without binding. It does nothing for arrow functions, and it is easy to forget, so most codebases prefer an arrow wrapper.
A bound function cannot be bound again. Calling bind, call, or apply on it later does not change its this:
function whoAmI() {
return this.name;
}
const bound = whoAmI.bind({ name: 'first' });
console.log(bound.call({ name: 'second' })); // 'first'
console.log(bound.bind({ name: 'third' })()); // 'first'Choosing a Fix
| Approach | Per-instance cost | Overridable by subclass | super works | Stable reference |
|---|---|---|---|---|
| Arrow at call site | New function per call site | Yes | Yes | No |
| Bind in constructor | One function per bound method | Yes | Yes | Yes |
| Arrow function field | One function per field | No, shadows subclass methods | No | Yes |
| `thisArg` parameter | None | Yes | Yes | Not applicable |
Some rules of thumb:
- For one-off callbacks such as
setTimeoutorthen, wrap the call in an arrow at the call site. - For listeners you must remove later, or methods you hand out often, bind in the constructor.
- Use arrow fields for leaf classes that will not be subclassed, where short code matters more than overriding.
Exercises
Exercise
A class has a method save() that reads this.data. Calling promise.then(store.save) throws "Cannot read properties of undefined (reading 'data')". Explain why and give two fixes.
Show answer
store.save passes only the function. The promise calls it plainly, so in strict-mode class code this is undefined. Fixes: write promise.then((result) => store.save(result)), or add this.save = this.save.bind(this); in the constructor so store.save is already bound.
Exercise
A base class declares render = () => 'base'; and a subclass declares a method render() { return 'child'; }. What does new Subclass().render() return, and how would you restructure the base class so the subclass override works while keeping render safe to pass as a callback?
Show answer
It returns 'base', because the arrow field is an own property of the instance and shadows the subclass's prototype method. Make render() a normal method in the base class and add this.render = this.render.bind(this); in the base constructor. Inside the constructor, this.render resolves to the subclass override, so the bound copy is the subclass version.
Exercise
Why does el.removeEventListener('click', this.onClick.bind(this)) fail to remove a listener added with the same expression?
Show answer
Each call to bind returns a new function object. removeEventListener compares by identity, so the second bound function does not match the one that was added. Store the bound function once, for example in the constructor, and pass that same reference to both calls.