Sub topic 7
Locking this with bind
This chapter assumes you know how plain calls and method calls set this, and that you have used call and apply to pass a this value for a single call. It also assumes you are comfortable with closures, because bind is easiest to understand as a closure that remembers a this value.
call and apply set this for one call. Most lost-binding bugs happen later, though: a method gets handed to a timer, an event system, or another module, and that code calls it as a plain function. You can't add .call(obj) to code you don't control. Function.prototype.bind solves this. It returns a new function whose this is fixed in advance, and no later call site can change it.
What bind Returns
fn.bind(thisArg, ...args) does not call fn. It creates a bound function, a separate function object that wraps fn. When you call the bound function, it calls fn with thisArg as this, the stored args first, and then any arguments passed in at call time.
'use strict';
const counter = {
count: 0,
increment() {
this.count++;
return this.count;
}
};
const inc = counter.increment; // detached: this will be undefined
const boundInc = counter.increment.bind(counter);
console.log(boundInc()); // 1
console.log(boundInc()); // 2
setTimeout(boundInc, 0); // still uses counter as this
setTimeout(() => console.log(counter.count), 10); // 3
try {
inc();
} catch (e) {
console.log(e instanceof TypeError); // true
}The original counter.increment does not change. bind leaves the target function alone and creates a new wrapper each time you call it. This matters later, when we look at identity and event listeners.
A Working Model: bind as a Closure
The term "hard binding" comes from the pattern people wrote before bind existed. It shows the whole idea in a few lines:
function hardBind(fn, thisArg, ...presetArgs) {
return function bound(...laterArgs) {
return fn.apply(thisArg, [...presetArgs, ...laterArgs]);
};
}
const user = {
name: 'Ada',
describe(role) {
return `${this.name} (${role})`;
}
};
const describeAda = hardBind(user.describe, user);
console.log(describeAda('admin')); // 'Ada (admin)'
console.log(describeAda.call({ name: 'Eve' }, 'x')); // 'Ada (x)'The wrapper ignores its own this and always calls fn.apply(thisArg, ...). That explains why call can't override it: call sets this on the wrapper, and the wrapper never reads it.
Use this as your mental model, but keep in mind that the native bind differs from it in several ways that the next sections cover. The native version cooperates with new, sets name and length, and has no prototype property.
Partial Application
The arguments after thisArg are stored and placed before any arguments passed at call time. This is partial application: you fix the leading parameters and get a function that takes the rest.
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const ada = { name: 'Ada' };
const greetAda = greet.bind(ada, 'Hey');
console.log(greetAda('.')); // 'Hey, Ada.'
console.log(greetAda('!')); // 'Hey, Ada!'You can use bind for partial application even when the function ignores this. By convention you pass null as the first argument:
function multiply(a, b) {
return a * b;
}
const double = multiply.bind(null, 2);
console.log([1, 2, 3].map(double)); // [2, 4, 6]Rebinding Does Not Work
After a function is bound, binding it again cannot change this. Calling call or apply on it can't either. The second bind wraps the first bound function, and the first one still discards whatever this it receives.
function whoAmI() {
return this.id;
}
const first = whoAmI.bind({ id: 'first' });
const second = first.bind({ id: 'second' });
console.log(first()); // 'first'
console.log(second()); // 'first'
console.log(first.call({ id: 'call' })); // 'first'Extra arguments do add up across layers. Each bind appends its preset arguments after the ones already stored:
function list(a, b, c) {
return [a, b, c];
}
const l1 = list.bind(null, 1);
const l2 = l1.bind({ ignored: true }, 2);
console.log(l2(3)); // [1, 2, 3]This behavior is the reason to use bind. It is also a trap when you receive a function from somewhere else. If a library gives you an already bound callback, you can't redirect its this. When this doesn't change and you can't see why, check fn.name for a bound prefix.
The Exception: new
One kind of call does override a bound this. When you call a bound function with new, the stored this is ignored and a fresh object is created, while the stored arguments are still used. The chapter on binding precedence explains where this fits. For now, the important point is that bind does not block construction:
function Point(x, y) {
this.x = x;
this.y = y;
}
const PointOnYAxis = Point.bind({ ignored: true }, 0);
const p = new PointOnYAxis(5);
console.log(p.x, p.y); // 0 5
console.log(p instanceof Point); // true
console.log(p instanceof PointOnYAxis); // trueinstanceof works with the bound function because it checks the target's prototype. The simple hardBind wrapper above can't do this. With new hardBind(...), the wrapper creates its own object, throws it away, and calls fn with the stored this.
Properties of Bound Functions
A bound function is a different object from its target, and you can see this from its properties.
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const greetAda = greet.bind({ name: 'Ada' }, 'Hey');
console.log(greetAda.name); // 'bound greet'
console.log(greet.length); // 2
console.log(greetAda.length); // 1, one parameter already supplied
console.log('prototype' in greetAda); // false
console.log(greetAda === greet); // false| Property | Target function | Bound function |
|---|---|---|
| `name` | `'greet'` | `'bound greet'` |
| `length` | Declared parameter count | Target length minus preset args, never below 0 |
| `prototype` | Present for regular functions | Absent |
| Reacts to `call`/`apply` this | Yes | No |
| Usable with `new` | If target is constructible | If target is constructible |
The bound prefix shows up in stack traces and profiler output, so it helps you find where a binding was made. Some libraries read length to decide how to call a function. Express error middleware is one example, because it is recognized by having four parameters. Binding preset arguments lowers length and can change how that code treats your function.
What thisArg Becomes: null, undefined, and Primitives
How the thisArg value is treated depends on whether the target function is strict, not on the code that calls bind.
function sloppyThis() {
return this;
}
function strictThis() {
'use strict';
return this;
}
console.log(sloppyThis.bind(null)() === globalThis); // true
console.log(strictThis.bind(null)()); // null
console.log(typeof sloppyThis.bind(42)()); // 'object' (boxed Number)
console.log(typeof strictThis.bind(42)()); // 'number'In sloppy mode, null and undefined are replaced with globalThis, and primitives are wrapped in objects. In strict mode, which includes modules and class bodies, the value is passed through unchanged. So bind(null, ...) for partial application is safe in strict code. In sloppy code, an accidental this.x = ... inside the target writes to the global object.
Common Patterns
Binding once in a constructor
Before class fields existed, the usual fix for methods passed as callbacks was to bind them in the constructor and save the bound version on the instance:
class Clock {
constructor() {
this.ticks = 0;
this.tick = this.tick.bind(this); // own property shadows the prototype method
}
tick() {
this.ticks++;
}
}
const clock = new Clock();
const { tick } = clock;
tick();
tick();
console.log(clock.ticks); // 2The right side reads tick from the prototype. The assignment then creates an own property on the instance that holds a bound copy. Every instance gets its own bound function. The chapter on classes compares this with arrow class fields.
Keeping a reference for removal
removeEventListener and similar APIs match listeners by identity. Because each bind call returns a new function, binding inline means you can never remove the listener:
const target = new EventTarget(); // available in browsers and Node 15+
const logger = {
prefix: '[log]',
handle(event) {
console.log(this.prefix, event.type);
}
};
// Wrong: two different function objects
target.addEventListener('ping', logger.handle.bind(logger));
target.removeEventListener('ping', logger.handle.bind(logger)); // removes nothing
// Right: bind once, keep the reference
const boundHandle = logger.handle.bind(logger);
target.addEventListener('ping', boundHandle);
target.dispatchEvent(new Event('ping')); // both listeners log '[log] ping'
target.removeEventListener('ping', boundHandle);
target.dispatchEvent(new Event('ping')); // only the leaked listener logsThe same identity rule affects memoization, dependency arrays in UI frameworks, and any Set of callbacks. Code that binds inside a render function or a loop creates a new function every time.
Borrowing a method permanently
bind can turn a method into a standalone function that is tied to a specific receiver:
const hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty);
console.log(hasOwn({ a: 1 }, 'a')); // true
console.log(hasOwn({ a: 1 }, 'b')); // falseHere call is the target and hasOwnProperty is its fixed this. So hasOwn(obj, key) runs hasOwnProperty.call(obj, key). Modern code would use Object.hasOwn, but you will still find this pattern in older libraries.
When Not to Use bind
| Situation | Better choice | Reason |
|---|---|---|
| One immediate call with a chosen `this` | `call` / `apply` | No extra function object |
| A callback inside a method that needs the method's `this` | Arrow function | Reads the enclosing `this` directly |
| An API that accepts `thisArg` | Pass `thisArg` | The API sets `this` for you |
| A function that must work with many receivers | Leave it unbound | Binding stops reuse |
| A function arriving from untrusted or unknown code | Don't assume you can rebind | It may already be bound |
bind is the right tool when you hand a function to code you don't control and you need a stable reference, either to remove it later or to compare it by identity.
Exercises
Exercise
In strict mode, what does this code log, and why? const o = { v: 1, get() { return this.v; } }; const g = o.get.bind({ v: 2 }); const h = g.bind({ v: 3 }); console.log(h.call({ v: 4 }), h.name);
Show answer
It logs 2 'bound bound get'. The first bind fixes this to { v: 2 }. The second bind and the call wrap that bound function, but the inner bound function discards any this it receives. Each bind adds a "bound " prefix to the name.
Exercise
A component runs 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 the bug and fix it.
Show answer
Each call to bind returns a new function object, and removeEventListener matches listeners by identity, so the remove call never finds the listener that was added. Bind once and store the result, for example this.onResize = this.onResize.bind(this) in the constructor, then pass that same this.onResize to both addEventListener and removeEventListener.
Exercise
Given function Pair(a, b) { this.a = a; this.b = b; } and const P = Pair.bind({ a: 'x' }, 1);, what are new P(2).a, new P(2).b, P.length, and 'prototype' in P?
Show answer
The values are 1, 2, 1, and false. new ignores the bound this, so a fresh object is created, and the preset argument 1 still goes in first. length is 2 minus 1 preset argument. Bound functions have no prototype property, and instanceof uses the target's prototype instead.
Exercise
Why does function f() { return this; } f.bind(null)() return globalThis, while the same code with 'use strict' inside f returns null?
Show answer
The thisArg is processed according to the target function's mode. A sloppy-mode target replaces null and undefined with globalThis and wraps primitives in objects. A strict target receives the value unchanged. The mode of the code that called bind does not matter.