Sub topic 11
Methods, Callbacks, and Class Field Arrows
Earlier chapters showed how this is set for regular functions and arrow functions. This chapter applies those rules in the three places where they cause the most bugs: object methods, callbacks, and class fields. This chapter assumes you know method shorthand in object literals, basic class syntax, and the rule that an arrow function takes this from the scope around it. The examples run in Node.js as CommonJS scripts, for example node methods.js.
The Core Rule, Applied
A regular function gets its this when it is called, from how it is called. An arrow function gets its this when it is created, from the code around it. Most mistakes come from using the wrong rule for the job:
- A method needs the object it was called on. That is call-time binding, so use a regular function.
- A callback inside a method usually needs the method's
this, not whatever the caller supplies. That is creation-time binding, so use an arrow. - A handler passed around detached from its object needs
thisfixed for good. That calls for an arrow class field orbind.
Object Methods: Use Method Shorthand
Writing an arrow function as an object literal property looks tidy, but the arrow never sees the object. An object literal does not create a scope, so the arrow's this is whatever this was where the literal was written.
const user = {
name: 'Ada',
greetMethod() {
return `Hi, ${this.name}`;
},
greetArrow: () => `Hi, ${this?.name}`,
};
console.log(user.greetMethod()); // Hi, Ada
console.log(user.greetArrow()); // Hi, undefinedIn a CommonJS module, top-level this is module.exports, an empty object. In an ES module it is undefined. The ?. keeps the example from throwing in either case. Both cases print undefined, because the arrow captured the module's this instead of user.
Method shorthand (greetMethod() { ... }) also has a benefit beyond this: it lets the method use super inside objects and classes. An arrow property cannot do that.
Callbacks Inside Methods: Use Arrows
The opposite problem shows up one level deeper. Inside a method, you often pass a callback to map, forEach, setTimeout, or a promise's then. The code that calls your callback decides its this, and it almost never chooses your object.
'use strict';
const formatter = {
prefix: '>',
formatArrow(items) {
return items.map(item => `${this.prefix} ${item}`);
},
formatRegular(items) {
return items.map(function (item) {
return `${this.prefix} ${item}`;
});
},
formatThisArg(items) {
return items.map(function (item) {
return `${this.prefix} ${item}`;
}, this);
},
};
console.log(formatter.formatArrow(['a', 'b'])); // [ '> a', '> b' ]
console.log(formatter.formatThisArg(['a', 'b'])); // [ '> a', '> b' ]
try {
formatter.formatRegular(['a', 'b']);
} catch (e) {
console.log(e instanceof TypeError); // true
}In strict mode, map calls the regular callback with this set to undefined, so reading this.prefix throws. In sloppy mode this would be globalThis and you would silently get 'undefined a', which is worse. Array methods accept an optional thisArg as their second argument. It works, but it is easy to forget, and APIs such as setTimeout and then have no equivalent. The arrow is the usual fix: it reads this from formatArrow, which was called as formatter.formatArrow(...).
When the Caller Supplies this on Purpose
Some APIs deliberately call your callback with a useful this. DOM event listeners set this to the element. Node's EventEmitter sets it to the emitter. Here an arrow throws that value away:
const { EventEmitter } = require('node:events');
const emitter = new EventEmitter();
emitter.on('ping', function () {
console.log(this === emitter); // true
});
emitter.on('ping', () => {
console.log(this === emitter); // false
});
emitter.emit('ping');If you rely on the caller's this, write a regular function. Many developers skip this pattern and use the event object or a closed-over variable instead. That works with either function form and makes the dependency obvious.
Class Methods Lose this When Detached
Class bodies run in strict mode. A prototype method that you pull off its instance, by destructuring it, storing it, or passing it as a callback, gets this === undefined when called.
class Greeter {
name = 'Ada';
greet() {
return `Hi, ${this.name}`;
}
}
const g = new Greeter();
const detached = g.greet;
try {
detached();
} catch (e) {
console.log(e instanceof TypeError); // true
}
setTimeout(g.greet, 0); // would also throw inside the timerThere are two standard fixes: an arrow function class field, and bind in the constructor.
Fix 1: Arrow Function Class Fields
A class field initializer runs once per instance, during construction, with this set to the new instance. An arrow created there captures that instance permanently.
const { EventEmitter } = require('node:events');
class Widget {
clicks = 0;
onClick = () => {
this.clicks++;
};
attach(emitter) {
emitter.on('click', this.onClick);
}
detach(emitter) {
emitter.off('click', this.onClick);
}
}
const bus = new EventEmitter();
const w = new Widget();
w.attach(bus);
bus.emit('click');
bus.emit('click');
w.detach(bus);
bus.emit('click');
console.log(w.clicks); // 2Because this.onClick is one stable function per instance, off can remove it. An inline arrow such as emitter.on('click', () => this.clicks++) could never be removed, because you would have no reference to pass to off.
Fix 2: bind in the Constructor
bind creates a new function whose this is fixed. Assigning it to the instance shadows the prototype method:
class Timer {
constructor(label) {
this.label = label;
this.tick = this.tick.bind(this);
}
tick() {
return `${this.label} tick`;
}
}
const t = new Timer('A');
const { tick } = t;
console.log(tick()); // A tick
console.log(Object.hasOwn(Timer.prototype, 'tick')); // trueThe prototype method still exists here. That matters for the trade-offs below.
Trade-offs of Arrow Class Fields
Arrow fields are convenient, but they are not free. Each one is an own property of the instance, not a shared prototype method.
class Counter {
count = 0;
incrementArrow = () => {
this.count++;
return this.count;
};
increment() {
this.count++;
return this.count;
}
}
const a = new Counter();
const b = new Counter();
console.log(a.increment === b.increment); // true
console.log(a.incrementArrow === b.incrementArrow); // false
console.log('incrementArrow' in Counter.prototype); // false
console.log(Object.hasOwn(a, 'incrementArrow')); // trueMemory per Instance
Every instance gets its own function object. For a few UI components this costs nothing worth measuring. For hundreds of thousands of small objects, prototype methods are cheaper.
Inheritance and super
A field is installed on the instance right after the base constructor finishes. It therefore shadows any method of the same name further down the class chain, including subclass methods.
class Base {
handle = () => 'base field';
describe() {
return 'base method';
}
}
class Child extends Base {
handle() {
return 'child method';
}
describe() {
return `child + ${super.describe()}`;
}
}
const c = new Child();
console.log(c.handle()); // base field
console.log(c.describe()); // child + base methodChild.prototype.handle exists, but the instance's own handle property hides it. A subclass also cannot call super.handle() to reach the base arrow, because super looks on the prototype and the arrow is not there.
Testing and Mocking
Tools that patch Class.prototype.method, such as jest.spyOn(Widget.prototype, 'onClick'), cannot see arrow fields. You have to spy on each instance after it is constructed.
| Approach | Where the function lives | Safe to detach | Overridable in subclass | super access | Per-instance cost |
|---|---|---|---|---|---|
| Prototype method | Prototype | No | Yes | Yes | None |
| Arrow class field | Instance | Yes | Not cleanly | No | One function |
| `bind` in constructor | Both | Yes | Yes, via prototype | Yes | One bound function |
| Inline arrow at call site | Nowhere stored | Yes | Not applicable | Not applicable | One per call |
Common Errors
- Arrow as an object literal method.
thisis the module or outer scope. Use method shorthand. - Regular function callback inside a method.
thisisundefinedorglobalThis. Use an arrow. - Passing
obj.methodtosetTimeoutor a listener. The method is detached. Use an arrow field,bind, or wrap it in() => obj.method(). - Inline arrow listener you later need to remove. Store the function so you can pass the same reference to
offorremoveEventListener. - Arrow field with the same name as a subclass method. The field wins silently.
Exercise
Given const cart = { items: [1, 2], total: () => this.items.length };, what happens when a CommonJS script calls cart.total(), and how do you fix it?
Show answer
It throws a TypeError. The arrow's this is the module's this (module.exports, an empty object), so this.items is undefined and reading .length from it fails. Rewrite it as method shorthand, total() { return this.items.length; }, so this is cart when it is called as cart.total().
Exercise
A class Logger has a prototype method log() that reads this.prefix. You call setTimeout(logger.log, 100) and it throws. List two fixes that keep log overridable by subclasses.
Show answer
Either wrap the call at the call site, setTimeout(() => logger.log(), 100), or bind in the constructor with this.log = this.log.bind(this). Both keep log on the prototype, where a subclass can override it. Converting log to an arrow class field would fix the this problem, but subclass methods named log would then be shadowed.
Exercise
Why does emitter.off('data', () => this.handle()) fail to remove a listener that was added with emitter.on('data', () => this.handle())?
Show answer
Each arrow expression creates a new function object. The function passed to off is not the same reference as the one passed to on, so the emitter finds no match. Store the handler once, for example as an arrow class field onData = () => this.handle();, and pass this.onData to both on and off.