Intermediate · 6 of 17 · 15 min read
call, apply and bind
The three ways to say what this should be, which one calls immediately, and the borrowing and partial-application tricks they enable.
- call / apply / bind
Normally this is whatever the call site implies. These three methods let you state it outright.
Every function has them, because they live on Function.prototype.
The three, side by side
| Calls immediately | Arguments | Returns | |
|---|---|---|---|
fn.call(thisArg, a, b) |
yes | one by one | whatever fn returns |
fn.apply(thisArg, [a, b]) |
yes | as an array | whatever fn returns |
fn.bind(thisArg, a) |
no | pre-filled, one by one | a new function |
function introduce(greeting, punctuation) {
return `${greeting}, I am ${this.name}${punctuation}`;
}
const user = { name: 'Ana' };
console.log(introduce.call(user, 'Hi', '!')); // "Hi, I am Ana!"
console.log(introduce.apply(user, ['Hi', '!'])); // "Hi, I am Ana!"
const bound = introduce.bind(user, 'Hey');
console.log(bound('?')); // "Hey, I am Ana?"
console.log(typeof introduce.bind(user)); // "function" — nothing ran yet
A mnemonic that survives interviews: apply takes an array, call takes a comma list, bind takes its time.
call
Reads exactly like a normal call with the receiver moved to the front:
function greet(greeting) {
return `${greeting}, my name is ${this.name}`;
}
console.log(greet.call({ name: 'Gabriel' }, 'Hello')); // "Hello, my name is Gabriel"
console.log(greet.call({ name: 'Ana' }, 'Hola')); // "Hola, my name is Ana"
Passing null or undefined as the receiver means “no particular object” — in strict mode this
stays undefined:
'use strict';
function who() { return this; }
console.log(who.call(null)); // null in sloppy mode becomes globalThis; here: null
console.log(who.call(undefined)); // undefined
apply
Identical, except the arguments arrive as an array. Its historical use was spreading an array into a function that takes separate arguments:
const numbers = [5, 1, 9, 3];
console.log(Math.max.apply(null, numbers)); // 9 — the pre-ES6 spread
console.log(Math.max(...numbers)); // 9 — what you write today
The spread replaced most uses of apply, so the remaining ones are where the argument list is
genuinely a value you already hold:
function log(level, ...parts) {
return `[${level}] ${parts.join(' ')}`;
}
const collected = ['warn', 'disk', 'almost', 'full'];
console.log(log.apply(null, collected)); // "[warn] disk almost full"
const big = Array.from({ length: 200_000 }, (_, i) => i);
// Math.max(...big); // RangeError: Maximum call stack size exceeded
console.log(big.reduce((max, n) => (n > max ? n : max), -Infinity)); // 199999
bind
Returns a new function. The original is untouched, and the bound receiver can never be changed again:
function sayAge() {
return `I am ${this.age}`;
}
const boundToOne = sayAge.bind({ age: 33 });
console.log(boundToOne()); // "I am 33"
console.log(boundToOne.call({ age: 99 })); // "I am 33" — call cannot override it
const reBound = boundToOne.bind({ age: 50 });
console.log(reBound()); // "I am 33" — the second bind is ignored
The first bind wins, permanently. That is the snippet interviewers like, and the reason is that a
bound function’s internal receiver is set once at creation.
Fixing the lost-receiver bug
The everyday use:
const timer = {
seconds: 0,
tick() {
this.seconds += 1;
return this.seconds;
},
};
// setInterval(timer.tick, 1000); // TypeError — `this` is lost
const safe = timer.tick.bind(timer);
console.log(safe(), safe()); // 1 2
Partial application
Arguments passed to bind are pre-filled from the left, and the arguments at call time follow:
function multiply(a, b) {
return a * b;
}
const double = multiply.bind(null, 2);
const triple = multiply.bind(null, 3);
console.log(double(5), triple(5)); // 10 15
null as the receiver is the idiom for “this function does not use this, I only want the
pre-filled argument”. Only prefilling from the left is possible — for anything else, write a closure:
function multiply(a, b) { return a * b; }
const halve = (n) => multiply(n, 0.5); // a closure, for any argument position
console.log(halve(8)); // 4
Bound functions and new
A bound function can still be constructed, and new overrides the bound this — the one case where
the binding loses:
function Point(x, y) {
this.x = x;
this.y = y;
}
const Bound = Point.bind({ ignored: true }, 1);
const p = new Bound(2);
console.log(p.x, p.y); // 1 2
console.log(p instanceof Point); // true — the bound `this` was discarded
Also worth knowing: a bound function’s name is prefixed, and its length drops by the number of
pre-filled arguments.
function f(a, b, c) {}
const g = f.bind(null, 1);
console.log(g.name, g.length); // "bound f" 2
Method borrowing
The use that explains why these methods exist at all: running a method against an object it was not
written for. Array methods only need length and indexed properties, so they work on anything with
that shape.
function oldSchool() {
// `arguments` is array-like, not an array
console.log(Array.prototype.slice.call(arguments)); // [1, 2, 3]
console.log(Array.prototype.map.call(arguments, (n) => n * 2)); // [2, 4, 6]
console.log(Array.from(arguments)); // [1, 2, 3] — modern
}
oldSchool(1, 2, 3);
const arrayLike = { 0: 'a', 1: 'b', length: 2 };
console.log(Array.prototype.join.call(arrayLike, '-')); // "a-b"
The other classic is exact type detection, because Object.prototype.toString reports the internal
tag that typeof flattens:
const typeOf = (value) => Object.prototype.toString.call(value).slice(8, -1);
console.log(typeOf([])); // "Array"
console.log(typeOf(null)); // "Null"
console.log(typeOf(new Date())); // "Date"
console.log(typeOf(/x/)); // "RegExp"
console.log(typeof []); // "object" — all of the above are "object"
call is used rather than arrayLike.join() because the object does not have the method. Borrowing
is reaching into another prototype and pointing its method at your value.
Writing them yourself
A compact way to prove you understand what they do — and a question that does come up:
Function.prototype.myCall = function (thisArg, ...args) {
const key = Symbol('fn'); // a unique key, so nothing is overwritten
const target = thisArg ?? globalThis;
target[key] = this; // `this` is the function myCall was called on
const result = target[key](...args); // a method call, so `this` is target
delete target[key];
return result;
};
function greet(greeting) { return `${greeting}, ${this.name}`; }
console.log(greet.myCall({ name: 'Ana' }, 'Hi')); // "Hi, Ana"
The trick is that there is no primitive for “call with this receiver” — you temporarily make it a
method of the object, which is the only form that sets this by position.
Common mistakes
Expecting bind to call the function
Mistake. button.addEventListener('click', handler.bind(this)()) — note the extra ().
Why it fails. bind returns a function; the extra parentheses run it immediately and register
its return value, usually undefined, as the listener.
What to do instead. Pass the bound function itself, with no trailing call.
Re-binding an already bound function
Mistake. Passing an already-bound callback through another bind to “re-point” it.
Why it fails. The receiver is fixed at the first bind and later ones cannot change it.
What to do instead. Bind the original function, or wrap it in an arrow that calls it with the
receiver you want.
apply on a very large array
Mistake. Math.max.apply(null, hugeArray).
Why it fails. Each element becomes a stack argument, and enough of them overflow the stack.
What to do instead. reduce, or process in chunks.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
You can override the call site and state what this should be, and there are three tools for it.
What does this log?
function intro(greeting, punctuation) {
return greeting + ", " + this.name + punctuation;
}
const person = { name: "Ana" };
console.log(intro.apply(person, ["Hi", "!"]));Two of the three binding tools can be combined — and one of them wins.
What does this log?
function show() {
return this.id;
}
const bound = show.bind({ id: 1 });
console.log(bound.call({ id: 2 }));What is the difference between call() and apply()?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.