Developer publication Code and Cloud
Article JavaScript

Article

Introduction to call, apply, and bind

A practical introduction to JavaScript's `call()`, `apply()`, and `bind()` utilities with simple examples.

1 min read JavaScript
  • javascript

Here is a short introduction to the elusive call, apply, and bind methods in JavaScript.

Function.prototype.call()

The call() method calls a function with a given this value and arguments provided individually.

Suppose we have an object like this:

const alice = {
  username: 'Alice',
  age: 35,
  sayHello: function () {
    console.log(`Hello, ${this.username}`);
  },
};

and another object:

const bob = {
  username: 'Bob',
  age: 40,
};

To attach sayHello() to Bob, you can do this:

alice.sayHello.call(bob);

A more common use case is creating sayHello() as an independent function:

const alice = {
  username: 'Alice',
  age: 35,
};

const bob = {
  username: 'Bob',
  age: 40,
};

function sayHello() {
  console.log(`Hello, ${this.username}`);
}

sayHello.call(alice);
sayHello.call(bob);

The signature is:

call(thisArg[, arg1, arg2, /* …, */ argN])

Example:

function logDetails(city, state) {
  console.log(`Hello, ${this.username}. Age: ${this.age}. Lives in ${city}, ${state}`);
}

logDetails.call(alice, 'Buffalo', 'New York');
logDetails.call(bob, 'London');
logDetails.call(alice, ...['Buffalo', 'New York']);
logDetails.call(bob, ...['London']);

If the parameters are not provided, undefined will be used.

call() will not behave the same way with arrow functions, because arrow functions do not have their own this binding.

Function.prototype.apply()

apply() is almost identical to call(), except the arguments are passed as an array-like object.

apply(thisArg[, argsArray])

Example:

const func = function (action, fruit) {
  console.log(`${this.animalType} ${action} ${fruit}.`);
};

const monkeys = {
  animalType: 'Monkeys',
  getFood: function () {
    func.apply(this, ['eat', 'bananas']);
  },
};

monkeys.getFood();

Function.prototype.bind()

bind() creates a new function with this and optional arguments pre-bound.

const alice = {
  username: 'Alice',
  age: 35,
};

function sayHello(city, state) {
  console.log(`Hello, ${this.username} from ${city}, ${state}!`);
}

const helloAlice = sayHello.bind(alice, 'Buffalo', 'New York');
helloAlice();

The signature is the same shape as call():

bind(thisArg[, arg1, arg2, /* …, */ argN])

That is enough for an introduction. Feel free to explore the topic further from there.

Related articles

Keep reading

Search

Search the publication

Search articles, notes, projects, and topic pages without leaving the page.

Results are powered by a local Pagefind index generated at build time.