Sub topic 7
Keeping this Intact: bind and Arrow Functions
This chapter assumes you know how to write classes and methods in JavaScript, and you understand arrow functions and the difference between passing a function and calling it. You have also seen synchronous callbacks such as forEach and asynchronous ones such as setTimeout earlier in this tutorial.
Callbacks and methods often conflict. You pass counter.increment to forEach or setTimeout, and inside the method this is undefined, the global object, or some other object you never meant to use. This chapter covers why that happens, the four standard fixes, and when to use each.
How JavaScript Decides What this Is
this is not fixed when you define a function. For ordinary functions and methods, the call expression sets this at the moment the function is called. The rules, in order of precedence:
newcall:new Fn()setsthisto the newly created object.- Explicit binding:
fn.call(obj),fn.apply(obj), or a function produced byfn.bind(obj)setsthistoobj. - Method call:
obj.fn()setsthistoobj, the object before the dot. - Plain call:
fn()setsthistoundefinedin strict mode, or to the global object (globalThis) in sloppy mode.
Arrow functions ignore all four rules. An arrow function has no this of its own. It uses the this of the scope where it was written, the same way it would use any other outer variable.
The important point for callbacks is that the object is attached by the call, not by the function. Writing counter.increment without parentheses only reads a property, and the result is a plain function value. Once you pass that value to another function, the connection to counter is gone.
Watching this Get Lost
The loud failure: a TypeError
Class bodies always run in strict mode, so a detached class method gets this === undefined:
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count++;
}
}
const counter = new Counter();
const inc = counter.increment; // just a function value now
try {
inc(); // plain call: this is undefined
} catch (err) {
console.log(err.constructor.name + ': ' + err.message);
}
// TypeError: Cannot read properties of undefined (reading 'count')
try {
[1, 2].forEach(counter.increment); // forEach also makes a plain call
} catch (err) {
console.log(err.constructor.name);
}
// TypeErrorforEach holds a reference to the function and calls it as callback(element, index, array). Nothing before a dot means there is no this.
The quiet failure: the wrong object
A TypeError is the good outcome, because you see it right away. Some APIs call your callback with a this you didn't expect, and then the code keeps running and writes to the wrong object:
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count++;
}
}
const counter = new Counter();
setTimeout(counter.increment, 0);
setTimeout(() => {
console.log(counter.count); // 0, the increment went somewhere else
}, 10);Node.js calls timer callbacks with this set to the internal Timeout object. Browsers set it to window. In both cases this.count++ runs against an object that has no count property, stores NaN there, and throws nothing. The same thing happens with sloppy-mode functions outside classes, where a plain call gives this === globalThis. Your callback then reads and writes globals without any error.
Fix 1: Wrap the Call in an Arrow Function
The simplest fix is to make the call yourself, inside a small arrow function, so the call expression includes counter.:
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count++;
}
}
const counter = new Counter();
[1, 2].forEach(() => counter.increment());
setTimeout(() => counter.increment(), 0);
setTimeout(() => console.log(counter.count), 10); // 3The callback is now the arrow function. When it runs, it calls counter.increment() as a method call, so rule 3 applies. This fix also lets you control the arguments. forEach passes (element, index, array), and a method that takes optional parameters may misread them. With the wrapper you pass only what the method expects.
One detail matters for asynchronous code. The wrapper reads counter when it runs, not when you create it. If the variable is reassigned before the timer fires, the callback calls the new object. Usually that is fine. If you need the original object, use bind, which captures the object right away.
Fix 2: bind
fn.bind(obj) returns a new function whose this is permanently obj:
class Counter {
constructor() {
this.count = 0;
}
increment(step = 1) {
this.count += step;
}
}
const counter = new Counter();
const boundInc = counter.increment.bind(counter);
setTimeout(boundInc, 0);
boundInc.call({ count: 100 }); // call cannot override a bound this
const addFive = counter.increment.bind(counter, 5); // partial application
addFive();
setTimeout(() => console.log(counter.count), 10); // 7How bind behaves:
- The binding is permanent.
call,apply, and a secondbindcannot changethison a bound function. A later.bind(other)can still add more preset arguments, butthisstays the same. - It can preset arguments. Extra arguments to
bindare placed before the arguments the caller passes. That is howaddFiveworks. newbeats it. If you call a bound function withnew, the boundthisis ignored. This rarely matters for callbacks.- Each call creates a different function.
counter.increment.bind(counter) !== counter.increment.bind(counter). This matters when you need the same reference later.
That last point causes a common listener bug:
const { EventEmitter } = require('node:events');
class Logger {
constructor() {
this.lines = 0;
}
log(msg) {
this.lines++;
console.log(this.lines, msg);
}
}
const emitter = new EventEmitter();
const logger = new Logger();
emitter.on('msg', logger.log.bind(logger));
emitter.off('msg', logger.log.bind(logger)); // different function: removes nothing
emitter.emit('msg', 'still attached'); // 1 still attached
// Correct: bind once, keep the reference
const boundLog = logger.log.bind(logger);
emitter.on('msg', boundLog);
emitter.off('msg', boundLog);
emitter.emit('msg', 'only the first listener runs'); // 2 only the first listener runsThe same rule applies to inline arrow wrappers. You can only remove a listener if you kept a reference to the exact function you registered.
Fix 3: Pass thisArg Where the API Supports It
Many built-in array methods take an optional second argument that sets this for the callback: forEach, map, filter, some, every, find, findIndex, and Array.from (as its third argument).
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count++;
}
}
const counter = new Counter();
[1, 2, 3].forEach(counter.increment, counter);
console.log(counter.count); // 3This works without creating a function, but only for APIs that support it. setTimeout, addEventListener, fs.readFile, and most library callbacks have no thisArg parameter. An arrow function callback also ignores thisArg, because arrow functions ignore explicit binding.
Fix 4: Arrow Functions as Class Fields
You can define the method as an arrow function stored in an instance field. The arrow is created inside the constructor scope, so its this is always the instance:
class Counter {
count = 0;
increment = () => {
this.count++;
};
}
const counter = new Counter();
const inc = counter.increment;
inc();
[1, 2].forEach(counter.increment);
setTimeout(counter.increment, 0);
setTimeout(() => console.log(counter.count), 10); // 4The method can now be passed around freely. It is a common pattern in UI code where handlers are passed as props or listeners. It has costs:
- One function per instance. Prototype methods are shared by all instances. Arrow fields create a new function for every object, which uses more memory when you have thousands of instances.
- Not on the prototype.
Counter.prototype.incrementisundefined. Subclasses cannot callsuper.increment(), and test tools that stub prototype methods will miss it. - Overriding is confusing. If a subclass defines a prototype method named
increment, the parent's instance field still shadows it, because instance properties win over prototype properties.
When Arrow Functions Are the Bug
Lexical this helps when you want the outer this. It causes bugs when the API is meant to give your callback a this.
Arrow functions as object methods
const account = {
balance: 50,
showArrow: () => console.log(typeof this === 'object' && this !== null ? this.balance : this),
showMethod() {
console.log(this.balance);
},
};
account.showArrow(); // undefined (this is the module scope's this, not account)
account.showMethod(); // 50In a Node.js CommonJS module, the top-level this is module.exports, an empty object, so this.balance is undefined. In an ES module it is undefined itself. In both cases it is not account. Use method shorthand for object methods.
Callbacks that receive a meaningful this
Some APIs call ordinary functions with a useful this. Node's EventEmitter sets this to the emitter, and DOM addEventListener sets it to the element the listener is attached to (event.currentTarget).
const { EventEmitter } = require('node:events');
const emitter = new EventEmitter();
emitter.name = 'jobs';
emitter.on('done', function () {
console.log('regular:', this.name); // regular: jobs
});
emitter.on('done', () => {
console.log('arrow:', this === emitter); // arrow: false
});
emitter.emit('done');If you rewrite a function listener as an arrow function, code that relied on this stops working. The fix is to stop relying on this and use what the API passes in, such as event.currentTarget in the DOM, or a variable that holds the emitter.
Choosing a Fix
| Approach | Creates a function | Works with any API | Stable reference for removal | Main drawback |
|---|---|---|---|---|
| Arrow wrapper `() => obj.m()` | Each time it runs | Yes | Only if stored | Reads `obj` late, at call time |
| `obj.m.bind(obj)` | Each `bind` call | Yes | Only if stored | Easy to bind twice by mistake |
| `thisArg` parameter | No | Array methods only | Not applicable | Limited support |
| Arrow class field | Once per instance | Yes | Yes, `obj.m` itself | Not on prototype, memory per instance |
Rules of thumb:
- For one-off callbacks, use an inline arrow wrapper. It is the most readable option and lets you pick the arguments.
- For listeners you will remove later, bind once (or use an arrow field) and store the reference.
- For classes whose methods are routinely passed as callbacks, such as UI handlers, arrow fields are reasonable if you don't need inheritance on those methods.
- Prefer writing callbacks that don't depend on a dynamic
thisat all. Then none of these problems can occur.
Exercises
Exercise
The code below logs NaN or undefined instead of "Hello, Ada". Explain why and fix it in two different ways.
class Greeter {
constructor(name) { this.name = name; }
greet() { console.log('Hello, ' + this.name); }
}
const g = new Greeter('Ada');
setTimeout(g.greet, 0);
Show answer
g.greet is a property read that yields a plain function, so the connection to g is lost. The timer calls it with this set to the Timeout object in Node.js, or to window in a browser. Neither has a name property, so the output is "Hello, undefined". Fix 1: setTimeout(() => g.greet(), 0); performs a method call inside the arrow. Fix 2: setTimeout(g.greet.bind(g), 0); creates a function whose this is permanently g. A third option is to declare greet = () => { ... } as a class field.
Exercise
A component registers window.addEventListener('resize', this.onResize.bind(this)) in its setup and calls window.removeEventListener('resize', this.onResize.bind(this)) in its teardown. The handler keeps firing after teardown. Why, and what is the fix?
Show answer
Each bind call returns a new function, so the function passed to removeEventListener is not the one that was registered, and nothing is removed. Bind once and store the result, for example this.boundResize = this.onResize.bind(this) in the constructor, then pass this.boundResize to both calls. Defining onResize as an arrow class field also works, because this.onResize is then the same function every time.
Exercise
What does this code print, and why? const results = []; const collector = { results, add(x) { this.results.push(x * 2); } }; [1, 2, 3].forEach(collector.add, collector); [4].forEach((x) => collector.add(x), { results: [] }); console.log(results);
Show answer
It prints [2, 4, 6, 8]. The first forEach passes collector as thisArg, so add runs with this === collector and pushes 2, 4, 6. In the second call the callback is an arrow function, so forEach cannot change its this, and the arrow ignores the { results: [] } argument. The arrow calls collector.add(x) as a method call, so 8 also goes into collector.results, which is the same array as results.