Back to all questions

Explain the call, apply, and bind methods

Devs Hive

Devs Hive

Seen on interview: 3 users

This question comes up quite often in interviews. It may be phrased exactly like the title, or it may be asked like this: "Can we change this?" The answer is yes, we can, and for that JS has built-in methods such as call, apply і bind.

All three methods do the same thing: they let you explicitly set what this will be inside a function. In simple terms, we tell the function which object it should work with.

The differences between them are:

  1. How arguments are passed
  2. Whether the function is invoked immediately

For example, the call method accepts arguments separated by commas and invokes the function immediately. Here we explicitly specify that this inside greet will be the object { title: "Hello" }.

The apply method does the same thing as call: the function is invoked immediately, but the arguments are passed as an array.

function greet(name) {
console.log(this.title + " " + name);
}

greet.call({ title: "Hello" }, "John");

greet.apply({ title: "Hello" }, ["John"]);

The bind method, unlike the previous two, does not invoke the function immediately. Instead, it returns a new function that already has this bound. As for arguments, they are passed separated by commas, but to the new function. It is usually used when you need to pass a function elsewhere while preserving the correct this.

const boundGreet = greet.bind({ title: "Hello" });

boundGreet("John");

It is good practice to add that bind is an implementation of partial application, which in turn is the basis for a technique such as Currying.

Seen on interview?

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!