Sub topic 12
Callbacks, thisArg, and Event Handlers
This chapter assumes you already know the four binding rules (default, implicit, explicit, and new), how bind creates a hard-bound function, and how arrow functions take this from the scope around them. In this chapter those rules meet code you did not write, such as array methods, timers, promises, and the DOM.
A callback is a function you pass to some other code, which calls it later. The rule that matters most here is that you are not the caller. The API that runs your callback decides how to call it, so it decides this too. If you want to predict this inside a callback, you need to know how that particular API calls it.
Who Calls Your Callback Decides this
When you write items.forEach(fn), the expression fn is a reference to a function. No this is attached to it. Inside forEach, the engine calls fn in a way the specification defines. Each API makes one of a few choices:
- It passes
undefinedasthis, which gives default binding. - It passes a value you supplied, through a
thisArgparameter. - It passes a value of its own choosing, such as the element a listener is attached to or the emitter that fired an event.
An arrow function ignores all three choices because it has no this of its own. A function that was already hard-bound with bind also ignores them, because its bound this wins over any value passed by call.
The thisArg Parameter on Array Methods
Many built-in iteration methods accept an optional last argument called thisArg. The method calls your callback using that value as this. It works like callback.call(thisArg, element, index, array).
const scaler = {
factor: 3,
scale(nums) {
return nums.map(function (n) {
return n * this.factor;
}, this); // thisArg sets this inside the callback
}
};
console.log(scaler.scale([1, 2, 3])); // [3, 6, 9]If you leave out the second argument to map, the callback is called with undefined as this. In strict code, this.factor then throws a TypeError. In sloppy code it reads globalThis.factor, gets undefined, and the result is [NaN, NaN, NaN]. The sloppy case is worse because it fails silently.
Which methods accept thisArg
| Method | Accepts thisArg? | Notes |
|---|---|---|
| `forEach`, `map`, `filter` | Yes | Second argument |
| `some`, `every` | Yes | Second argument |
| `find`, `findIndex`, `findLast`, `findLastIndex` | Yes | Second argument |
| `flatMap` | Yes | Second argument |
| `Array.from(source, mapFn, thisArg)` | Yes | Third argument |
| `reduce`, `reduceRight` | No | Second argument is the initial value |
| `sort`, `toSorted` | No | The comparator gets `undefined` as `this` |
| `Map.prototype.forEach`, `Set.prototype.forEach` | Yes | Second argument |
The reduce row causes a common bug. Its second argument is the initial accumulator, so passing this there does not bind anything. Instead, it quietly turns your object into the starting value:
'use strict';
const cart = {
taxRate: 0.2,
items: [10, 20],
// Wrong: `this` becomes the initial accumulator, not the callback's this
totalWrong() {
return this.items.reduce(function (sum, price) {
return sum + price * (1 + this.taxRate);
}, this);
},
// Right: an arrow callback reads this from totalRight()
totalRight() {
return this.items.reduce((sum, price) => sum + price * (1 + this.taxRate), 0);
}
};
try {
cart.totalWrong();
} catch (e) {
console.log(e instanceof TypeError); // true: this is undefined inside the callback
}
console.log(cart.totalRight()); // 36thisArg and arrow functions
You cannot rebind an arrow function's this, so thisArg has no effect on it. That is usually fine, because the arrow already has the this you want. Problems come from mixing the two styles, for example by passing thisArg and expecting it to override an arrow function defined in some other scope. If the callback is an arrow function, drop thisArg. Keeping it suggests a binding that never happens.
const config = { factor: 10 };
const double = (n) => n * 2;
console.log([1, 2].map(double, config)); // [2, 4]; config is ignored
function useFactor(n) {
return n * this.factor;
}
console.log([1, 2].map(useFactor, config)); // [10, 20]Primitive thisArg values
If you pass a primitive such as a string or number as thisArg, strict and sloppy callbacks receive different things. A sloppy-mode function boxes the primitive into a wrapper object. A strict-mode function receives the primitive unchanged.
function sloppyType() {
return typeof this;
}
function strictType() {
'use strict';
return typeof this;
}
console.log([0].map(sloppyType, 'abc')); // ['object'] (a String wrapper)
console.log([0].map(strictType, 'abc')); // ['string']This rarely matters in practice. It does explain why this === 'abc' comes out false inside a sloppy callback.
Timers and Promises
Timers and promises have no thisArg, and each environment calls their callbacks in its own way.
setTimeoutandsetIntervalin browsers call a regular function callback with the globalwindowasthis, even when the callback is strict code, because the browser passeswindowexplicitly.- The same functions in Node.js pass the
Timeoutobject that the call returned. - Promise reaction callbacks passed to
then,catch, andfinallyare called withundefinedasthis. A strict callback seesundefined, and a sloppy one seesglobalThis.
'use strict';
const job = {
name: 'backup',
run() {
Promise.resolve().then(function () {
console.log(this); // undefined
});
Promise.resolve().then(() => {
console.log(this.name); // 'backup'
});
}
};
job.run();DOM Event Handlers
Browsers do give this a useful value in event listeners. When a regular function is registered with addEventListener, the browser calls it with this set to the element the listener is attached to. That element is the same one exposed as event.currentTarget.
const button = document.querySelector('button');
button.addEventListener('click', function (event) {
console.log(this === event.currentTarget); // true
});
button.addEventListener('click', (event) => {
// this comes from the surrounding scope, not the element
console.log(event.currentTarget);
});currentTarget vs target
The difference between currentTarget and target matters when you use event delegation. With delegation, one listener on a parent element handles events from all of its children.
event.currentTarget, and sothisin a regular function listener, is the element the listener is registered on.event.targetis the innermost element where the event started.
// HTML: <ul id="menu"><li><span>Open</span></li></ul>
const menu = document.getElementById('menu');
menu.addEventListener('click', function (event) {
console.log(this.id); // 'menu'
console.log(event.target.tagName); // 'SPAN' if the text was clicked
console.log(event.target.closest('li')); // the <li> that was clicked
});A common mistake is to write this.classList.add('active') and expect it to change the clicked item, when this is actually the container.
Use event.currentTarget in modern code
Inside a class or a component, you usually need this to be your instance and not the element. The listener's element is still available as event.currentTarget, so you lose nothing by using an arrow function or a bound method. Reading event.currentTarget also makes the code clear to readers who are not thinking about binding rules.
Inline handler attributes
Inline attributes such as onclick="..." also run with this as the element. However, the attribute's code is wrapped in a generated function, so calling another function from it is a plain call:
// HTML: <button onclick="report()">Go</button>
// <button onclick="reportWith(this)">Go</button>
function report() {
console.log(this); // globalThis in sloppy scripts, not the button
}
function reportWith(el) {
console.log(el.tagName); // 'BUTTON'
}To get the element into the function, pass this as an argument. Better still, use addEventListener and skip inline handlers.
The handleEvent object form
addEventListener also accepts an object that has a handleEvent method in place of a function. The browser then calls object.handleEvent(event), so this is the object. No binding step is needed, and it is easy to remove later because the object reference stays the same.
const tracker = {
clicks: 0,
handleEvent(event) {
this.clicks++;
console.log(event.type, this.clicks);
}
};
const button = document.querySelector('button');
button.addEventListener('click', tracker);
// Later:
button.removeEventListener('click', tracker);Removing bound listeners
Every call to bind returns a new function. To remove a listener, removeEventListener needs the same function reference you added, so this does nothing:
el.addEventListener('click', this.onClick.bind(this));
el.removeEventListener('click', this.onClick.bind(this)); // different function, not removedCreate the bound function once and keep the reference, either by binding in the constructor or by using an arrow class field:
class Toggle {
constructor(el) {
this.el = el;
this.on = false;
this.onClick = this.onClick.bind(this); // one stable reference
el.addEventListener('click', this.onClick);
}
onClick() {
this.on = !this.on;
this.el.textContent = this.on ? 'On' : 'Off';
}
destroy() {
this.el.removeEventListener('click', this.onClick); // same reference, removed
}
}
const toggle = new Toggle(document.querySelector('button'));An AbortController avoids keeping references entirely. You pass { signal: controller.signal } to addEventListener, and calling controller.abort() removes every listener registered with that signal.
Other Event APIs
Other libraries make their own choices about this. Node.js's EventEmitter calls a regular function listener with this set to the emitter:
const { EventEmitter } = require('node:events');
const emitter = new EventEmitter();
emitter.name = 'jobs';
emitter.on('done', function () {
console.log(this === emitter, this.name); // true 'jobs'
});
emitter.on('done', () => {
console.log(this === emitter); // false: arrow uses module-level this
});
emitter.emit('done');For any library you use, check its documentation to see what it passes as this. If it says nothing, assume undefined and write the callback so it does not depend on this.
Choosing an Approach
| Situation | Recommended callback | Why |
|---|---|---|
| Array method inside a method that needs the outer `this` | Arrow function | Lexical `this`, no extra argument |
| Reusable named function shared across objects | Regular function plus `thisArg` | Same function, different context per call |
| `reduce`, `sort`, timers, promises | Arrow function or `bind` | No `thisArg` available |
| DOM listener that only needs the element | Either; read `event.currentTarget` | Clear and independent of binding |
| DOM listener in a class that must be removed later | Arrow class field or bind once in the constructor | Stable reference for removal |
| Listener object with state | `handleEvent` object | `this` is the object, no binding needed |
Exercise
A class method runs return this.users.filter(function (u) { return u.age >= this.minAge; }); in a module, and it throws a TypeError. Give two different fixes and explain why the original fails.
Show answer
Module code is strict. filter calls the callback with undefined as this when no thisArg is given, so this.minAge reads a property of undefined. Fix 1: pass this as thisArg, as in filter(function (u) { ... }, this). Fix 2: use an arrow callback, filter((u) => u.age >= this.minAge), which takes this from the enclosing method.
Exercise
A listener is attached to a <table>. Inside a regular function handler, the code runs this.classList.toggle('selected') to highlight the clicked row, but the whole table gets the class. Why, and what should the code use?
Show answer
In a regular function listener, this is event.currentTarget, which is the element the listener is attached to (the table), not the element that was clicked. Use event.target.closest('tr') to find the clicked row and toggle the class on that element.
Exercise
A component calls window.addEventListener('resize', this.onResize.bind(this)) when it mounts and window.removeEventListener('resize', this.onResize.bind(this)) when it unmounts. The handler keeps firing after unmount. Explain and fix it.
Show answer
Each bind call creates a new function, so removeEventListener gets a different reference than the one added and removes nothing. Create the bound function once, for example with this.onResize = this.onResize.bind(this) in the constructor or by defining onResize as an arrow class field, and pass that same reference to both calls. Another option is to register with an AbortController signal and call abort() on unmount.