Skip to content

Call, Apply, and Bind Methods

Every function has three methods, call(), apply() and bind(), which set the value of this inside it. call() and apply() run the function straight away, while bind() returns a new function that can be run later. The this keyword page explains how this is normally decided.

The examples use one function that reads two properties from this:

function describe(format, year) {
return `${this.title} by ${this.author}, ${format}, ${year}`;
}
const book = { title: 'Brighton Rock', author: 'Graham Greene' };

call() takes the value for this first, then the function’s own arguments one by one:

console.log(describe.call(book, 'paperback', 1938));

This prints:

Brighton Rock by Graham Greene, paperback, 1938

apply() does the same job, but it takes the function’s arguments as a single array:

const details = ['hardback', 1938];
console.log(describe.apply(book, details));
console.log(describe.call(book, ...details));

This prints:

Brighton Rock by Graham Greene, hardback, 1938
Brighton Rock by Graham Greene, hardback, 1938

The second line gives the same result with call() and the spread syntax. Spread has replaced most uses of apply(), including the old way of finding the largest number in an array:

const temperatures = [14, 19, 11, 22];
console.log(Math.max.apply(null, temperatures));
console.log(Math.max(...temperatures));

This prints:

22
22

bind() does not run the function. It returns a copy with this fixed, and any arguments given to bind() are fixed as well, in front of the ones passed later:

const describeBook = describe.bind(book);
const describePaperback = describe.bind(book, 'paperback');
console.log(describeBook('audiobook', 2004));
console.log(describePaperback(1938));

This prints:

Brighton Rock by Graham Greene, audiobook, 2004
Brighton Rock by Graham Greene, paperback, 1938

Fixing some of the arguments in advance is called partial application, which Function Currying covers in more detail.

The commonest reason to use bind() is to pass a method somewhere else as a callback. A method passed on its own loses its object, so this is no longer the object when the method is finally called:

const oven = {
label: 'Oven',
report() {
console.log(`${this.label} is ready`);
},
};
setTimeout(oven.report, 10);
setTimeout(oven.report.bind(oven), 20);

This prints:

undefined is ready
Oven is ready

Wrapping the call in an arrow function, as in setTimeout(() => oven.report(), 10), fixes it in the same way.

An arrow function has no this of its own, because it uses the this of the code around it. Passing a different value through call(), apply() or bind() has no effect on it:

const bakery = {
name: 'Bakery',
greet() {
const welcome = () => `Welcome to ${this.name}`;
return welcome.call({ name: 'Butcher' });
},
};
console.log(bakery.greet());

This prints:

Welcome to Bakery

Steve Griffith covers this topic in his video JS Function Methods call( ), apply( ), and bind( ).