Sub topic 4
Keeping this and Arguments Intact
This chapter assumes you know regular functions and arrow functions, how this is set at call time, rest parameters, and Function.prototype.apply. It also builds on the trailing-edge debounce from the previous chapter.
A wrapper such as debounce stands between the caller and your real function. If the wrapper drops the caller's this or its arguments, your handler still runs, but it runs with the wrong data. This chapter shows how the wrapper forwards both and which mistakes break that.
How the wrapper forwards the call
Here is the debounce function again:
function debounce(fn, wait) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, args);
}, wait);
};
}
const counter = {
count: 0,
label: 'clicks',
report(step) {
this.count += step;
console.log(`${this.label}: ${this.count}`);
},
};
counter.debouncedReport = debounce(counter.report, 100);
counter.debouncedReport(1);
counter.debouncedReport(5); // after 100 ms, logs "clicks: 5"Three details make this work:
- The returned wrapper is a regular
function. When you callcounter.debouncedReport(5), JavaScript sets the wrapper'sthistocounter, just as it would for any method call. - The timer callback is an arrow function. Arrow functions have no
thisof their own and use thethisof the surrounding function. When the timer fires,thisinside the arrow is stillcounter. ...argsandapplymove the arguments. The rest parameter collects every argument into an array.fn.apply(this, args)then calls the original function with thatthisand those arguments spread back out.
The broken version
This version looks shorter, but it loses this:
function debounceBroken(fn, wait) {
let timerId;
return (...args) => {
clearTimeout(timerId);
timerId = setTimeout(() => fn(...args), wait);
};
}There are two faults. The outer arrow takes its this from where debounceBroken was defined, not from the caller. Also, fn(...args) is a plain call, so fn gets no this at all. In strict mode and ES modules, this is undefined and this.count throws a TypeError. In sloppy mode, this is the global object, this.count becomes NaN, and the code fails without any error.
Event handlers and `this`
When addEventListener calls a listener, it sets this to the element the listener is attached to. A correct wrapper passes that along:
const input = document.querySelector('#search');
input.addEventListener('input', debounce(function (event) {
console.log(this.value); // the input element's value
console.log(event.target.value); // also works
}, 300));Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Returning an arrow function as the wrapper | `this` is `undefined` or the global object | Return a regular `function` |
| Calling `fn(...args)` instead of `fn.apply(this, args)` | Method loses its object | Use `apply` or `call` |
| Using a regular `function` as the timer callback | `this` inside the callback is not the caller | Use an arrow callback, or save `const ctx = this` first |
| Using `arguments` inside an arrow | Gets the enclosing function's arguments, or a `ReferenceError` at top level | Use a rest parameter |
| Passing a method unbound, e.g. `debounce(obj.method)` and then calling the result standalone | `this` is lost at the call site | Call it as a method, or use `debounce(obj.method.bind(obj), wait)` |
Exercise
A teammate writes const save = debounce(editor.save, 500); and later calls save() on its own. Inside editor.save, this.content is undefined. The debounce implementation is correct. Why does this happen, and what are two ways to fix it?
Show answer
The wrapper forwards whatever this it receives. Calling save() on its own gives it no object, so this is undefined in strict mode, and editor.save runs without editor. One fix is to bind first: debounce(editor.save.bind(editor), 500). The other is to attach the wrapper to the object and call it as a method: editor.debouncedSave = debounce(editor.save, 500); editor.debouncedSave();.
Exercise
In the broken version, why would changing only fn(...args) to fn.apply(this, args) not be enough?
Show answer
Both the outer wrapper and the timer callback are arrow functions, so this inside them comes from the scope where debounceBroken was defined, not from the caller. apply would forward the wrong this. The outer wrapper must also be a regular function so that it receives the caller's this.