Sub topic 12
Callbacks, thisArg, and Event Handlers
This chapter assumes you know the binding rules covered earlier: default, implicit, explicit with call/apply, hard binding with bind, and lexical this in arrow functions. Here you apply them to the most common place this goes wrong, which is functions you hand to someone else to call.
Who Calls Your Callback?
When you pass a function as a callback, you give up the call site. The code that receives the callback decides how to invoke it, so it also decides this. That leaves you three options:
- Use an API that lets you pass the
thisvalue it should use (athisArgparameter). - Use a convention the API documents, such as DOM listeners receiving the element.
- Ignore the caller entirely by using an arrow function or a bound function.
The thisArg Parameter
Many built-in array methods take an optional last argument that becomes this inside a regular function callback. These include forEach, map, filter, some, every, find, findIndex, and flatMap, and Array.from takes it as its third argument.
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]Without the second argument to map, the callback is a plain function call. In strict code this would be undefined and this.factor would throw.
thisArg works only for regular functions. An arrow function ignores it, because an arrow has no this of its own to set:
'use strict';
const scaler = {
factor: 3,
scale(nums) {
// The arrow already uses scale()'s this, so no thisArg is needed
return nums.map((n) => n * this.factor);
}
};
console.log(scaler.scale([1, 2, 3])); // [3, 6, 9]
const ignored = [1].map(() => this, { factor: 99 });
console.log(ignored); // [undefined] at the top level of a strict scriptIn modern code the arrow version is the usual choice. thisArg is still useful when the callback is a named, reusable regular function that reads this.
DOM Event Handlers
When the browser calls a regular function registered with addEventListener, it sets this to the element the listener is attached to. That is the same value 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);
});event.currentTarget is different from event.target. target is the innermost element that was clicked, such as a <span> inside the button. currentTarget is the element whose listener is running now. Reading event.currentTarget works in both regular and arrow listeners, so it is the clearer habit.
Handlers That Are Methods
Passing a method as a listener detaches it from its object, and the browser then supplies the element as this:
class Counter {
count = 0;
increment() {
this.count++; // this is the button, not the Counter
}
}
const counter = new Counter();
document.querySelector('button').addEventListener('click', counter.increment);You can fix this with an arrow class field or with bind. If you use bind, keep the result. Each call to bind creates a new function, and removeEventListener needs the exact same reference you added:
class Counter {
count = 0;
constructor(button) {
this.button = button;
this.onClick = this.increment.bind(this); // store one bound reference
button.addEventListener('click', this.onClick);
}
increment() {
this.count++;
}
destroy() {
this.button.removeEventListener('click', this.onClick); // same reference
}
}
const c = new Counter(document.querySelector('button'));Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| `Cannot read properties of undefined` inside `map` callback | Regular function called with default binding | Use an arrow, or pass `thisArg` |
| `thisArg` seems ignored | Callback is an arrow function | Remove `thisArg` and rely on lexical `this` |
| Listener mutates the element, not your object | Method passed as listener, browser sets `this` to element | Arrow class field or stored `bind` |
| `removeEventListener` does nothing | Called `bind` twice, so the two references differ | Bind once and store the result |
| Arrow listener can't find the element via `this` | Arrows don't receive the element | Use `event.currentTarget` |
Exercise
What does this code log, and why? 'use strict'; const o = { tag: 'o', run(list) { return list.filter(function () { return this === o; }); } }; console.log(o.run([1, 2]).length);
Show answer
It logs 0. The callback is a regular function called by filter with no thisArg, so default binding applies and this is undefined in strict mode. The test fails for every element. Passing this as the second argument to filter, or using an arrow function, would make it log 2.
Exercise
A component calls el.addEventListener('click', this.handle.bind(this)) in setup and el.removeEventListener('click', this.handle.bind(this)) in teardown. Why does the listener keep firing, and how do you fix it?
Show answer
Each bind call returns a new function, so removeEventListener receives a reference that was never added and does nothing. Bind once, store it (for example this.boundHandle = this.handle.bind(this)), and pass that stored reference to both calls. An arrow class field also works, because it gives each instance a single stable function.