Sub topic 7
Keeping this Intact: bind and Arrow Functions
This chapter assumes you know how JavaScript classes and methods work, how arrow functions differ in syntax from regular functions, and how callbacks are passed and invoked (covered in earlier chapters). It explains why a method passed as a callback often loses its this, and gives three reliable ways to keep it.
Why this Gets Lost
In a regular function or method, this is not fixed when you write the function. It is decided at call time, by how the function is called:
counter.increment()is a method call, sothisiscounter.fn()is a plain call, sothisisundefinedin strict mode, or the global object in sloppy mode.
When you pass counter.increment as a callback, you pass only the function. The object it came from stays behind. Later, the receiving code calls it as callback(item), which is a plain call. Class bodies always run in strict mode, so this becomes undefined.
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count++;
}
}
const counter = new Counter();
try {
[1, 2].forEach(counter.increment);
} catch (err) {
console.log(err.constructor.name, '-', err.message);
// TypeError - Cannot read properties of undefined (reading 'count')
}Fix 1: bind
Function.prototype.bind returns a new function whose this is permanently set to the value you give it. No later call style can change it.
const bound = counter.increment.bind(counter);
[1, 2].forEach(bound);
setTimeout(bound, 0);Fix 2: Wrap in an Arrow Function
Arrow functions have no this of their own. They use the this of the scope where they were written. Wrapping the call restores the method-call form:
[1, 2].forEach(() => counter.increment());Here counter.increment() is a method call again, so this is counter. The wrapper also lets you control arguments. forEach passes (item, index, array), and the wrapper passes none of them.
Fix 3: Arrow Function Class Fields
If a method is often used as a callback, for example a click handler, define it as a class field holding an arrow function. Each instance gets its own copy, and that copy's this is the instance.
class Clicker {
clicks = 0;
handleClick = () => {
this.clicks++;
};
}
const clicker = new Clicker();
const handler = clicker.handleClick;
handler();
handler();
console.log(clicker.clicks); // 2Some APIs Take a thisArg
forEach, map, filter, some, and every accept an optional second argument that is used as this for the callback:
[1, 2].forEach(counter.increment, counter);This works, but readers often miss it, and timers and event APIs don't offer it.
Choosing a Fix
| Approach | Best for | Trade-off |
|---|---|---|
| `fn.bind(obj)` | Passing an existing method once | Creates a new function each time you call `bind` |
| `() => obj.method()` | Inline callbacks, adjusting arguments | New function on each render or loop pass |
| Arrow class field | Handlers reused across many calls | One function per instance, not shared on the prototype, and absent from `super` |
| `thisArg` parameter | Array iteration methods | Only some APIs support it |
Arrow Functions Are Not Always the Answer
Some APIs deliberately set this for you. Examples are DOM listeners (this is the element) and Node.js EventEmitter listeners (this is the emitter). If you write such a callback as an arrow function, it ignores the this the API provides. Use a regular function there, or read event.currentTarget instead.
Exercise
What does this code log, and why? Give a one-line fix that makes it log 1. class Timer { constructor() { this.ticks = 0; } tick() { this.ticks++; } start() { setTimeout(this.tick, 0); setTimeout(() => console.log(this.ticks), 10); } } new Timer().start();
Show answer
It logs 0. this.tick is passed without its object, so the timer calls tick with a different this (window in browsers, a Timeout object in Node.js). this.ticks++ then changes that object, not the Timer. The logging arrow function keeps the Timer as this, so it prints the unchanged 0. Fix: setTimeout(() => this.tick(), 0) or setTimeout(this.tick.bind(this), 0).
Exercise
A component registers window.addEventListener('resize', this.onResize.bind(this)) and later calls window.removeEventListener('resize', this.onResize.bind(this)). The listener keeps firing. Why, and how do you fix it?
Show answer
Each bind call returns a new function, so the function passed to removal is not the one that was registered. Bind once and store the result, for example this.boundResize = this.onResize.bind(this) in the constructor, or define onResize as an arrow class field. Then pass that same reference to both calls.