Sub topic 7
Locking this with bind
This chapter assumes you know how method calls set this and why extracting a method loses it. It also assumes you have used call and apply. Those two methods set this for a single call. bind sets it permanently: it returns a new function whose this stays the same no matter how that function is later called. This is called hard binding.
What bind returns
fn.bind(thisArg, ...args) does not call fn. It creates a bound function, which is a wrapper that remembers three things:
- the target function (
fn) - the bound
thisvalue (thisArg) - any leading arguments you supplied
When you call the bound function, it ignores the this from its own call site. It calls the target with the stored this, then the stored arguments, then whatever arguments you pass at call time.
Fixing an extracted method
In the earlier lost-binding example, counter.increment broke as soon as it was stored in a variable. With bind, the extracted function keeps working, including when you pass it as a callback:
'use strict';
const counter = {
count: 0,
increment() {
this.count++;
return this.count;
}
};
const inc = counter.increment.bind(counter);
console.log(inc()); // 1
setTimeout(() => console.log(inc()), 0); // 2, the timer cannot change thisThe original counter.increment is unchanged. bind creates a separate function and leaves the method on the object alone.
A bound this cannot be changed
Once a function is bound, call, apply, a second bind, and method-call syntax all fail to change its this:
function whoAmI() {
return this.name;
}
const a = { name: 'a' };
const b = { name: 'b' };
const boundA = whoAmI.bind(a);
console.log(boundA.call(b)); // 'a'
console.log(boundA.bind(b)()); // 'a', rebinding has no effect on this
const holder = { name: 'holder', whoAmI: boundA };
console.log(holder.whoAmI()); // 'a', implicit binding is ignoredPartial application
The extra arguments to bind are fixed in front of the call-time arguments. You can use this to preset parameters even when the function never reads this. By convention, pass null as the thisArg in that case:
function multiply(a, b) {
return a * b;
}
const double = multiply.bind(null, 2);
console.log(double(5)); // 10
console.log(double.name); // 'bound multiply'
console.log(double.length); // 1, one parameter left to fillIn strict code, the target sees this as exactly null. In sloppy code, null and undefined are replaced with globalThis. If the function does use this, passing null can therefore make it write to the global object without any warning.
Common mistakes
Each bind call makes a new function
Two calls to bind with the same arguments return two different functions. This breaks APIs that compare functions by identity, such as removeEventListener:
const target = new EventTarget();
const logger = {
prefix: '[log]',
log(event) {
console.log(this.prefix, event.type);
}
};
target.addEventListener('ping', logger.log.bind(logger));
target.removeEventListener('ping', logger.log.bind(logger)); // removes nothing
const boundLog = logger.log.bind(logger);
target.addEventListener('ping', boundLog);
target.removeEventListener('ping', boundLog); // works: same reference
target.dispatchEvent(new Event('ping')); // '[log] ping' once, from the first listenerBind once, store the result, and reuse that reference.
Binding too early or to the wrong object
bind captures the object at the moment you call it. If you bind to an object and later replace the variable that pointed to it, the bound function still uses the old object.
Binding in hot paths
Calling bind inside a render loop or a frequently called function creates a new function every time. Usually the cost is small. The bigger problem is that each new reference defeats identity checks, such as memoization or listener removal.
| Need | Tool |
|---|---|
| Set `this` for a single call | `call` / `apply` |
| Pass a method as a callback and keep its `this` | `bind` (or an arrow function, covered later) |
| Preset leading arguments | `bind(null, ...)` |
| Remove a listener later | Store the bound function in a variable |
Exercise
Given function show() { return this.v; }, const f = show.bind({ v: 1 });, and const g = f.bind({ v: 2 });, what do g() and f.call({ v: 3 }) return, and why?
Show answer
Both return 1. f is hard-bound to { v: 1 }. Binding f again creates g, but g passes its this to f, and f ignores it. call cannot override a bound this either.
Exercise
A class constructor runs window.addEventListener('resize', this.onResize.bind(this)), and a destroy method runs window.removeEventListener('resize', this.onResize.bind(this)). The listener keeps firing after destroy. Why does this happen, and how do you fix it?
Show answer
Each bind call returns a new function, so removeEventListener receives a different reference than the one that was added. Store the bound function once, for example this.boundResize = this.onResize.bind(this), and pass this.boundResize to both the add and remove calls.