⚡ JavaScript: Fix a Debounced Method Losing this on a Class
A debounce helper wraps a plain function reference and returns a new function that calls the original after a delay. When the wrapped function is a class’s regular method, passed directly into the helper, the debounced wrapper eventually invokes the original as a bare function call once its timer fires – so this inside it is undefined in strict mode, not the instance, even though calling the method directly without debouncing worked fine because it was always called as instance.method().
🔎 The Problem
class SearchBox {
constructor() {
this.save = debounce(this.save, 300); // bound later, not here
}
save(value) {
this.state.lastSaved = value; // 'this' is undefined once the
} // debounce timer finally calls it
}
✅ Fix: Bind This Before Debouncing, Not After
- Bind the method to the instance before debouncing it –
this.save = debounce(this.save.bind(this), 300)– so the wrapped function always calls the original with the rightthis, regardless of how the timer later invokes it. - Alternatively, debounce an arrow function that closes over
thislexically –this.save = debounce(() => this.doSave(), 300)– rather than debouncing the method reference itself. - Add a test that actually calls the debounced version after the delay elapses, rather than only confirming the function object exists, since a method that reads
thisdeep in its body can pass a superficial smoke test that never waits for the timer.
🚨 Why This Is Dangerous
- This bug only shows up after the debounce delay actually elapses, so a quick manual test that clicks and immediately checks the result can look completely fine while the real, delayed invocation silently throws or operates on the wrong object.
A debounce wrapper controls when a function runs, never what it runs as – binding this is still your job, delay or not.

