DEV Community

Amandeep Singh
Amandeep Singh

Posted on • Edited on

call(), apply() & bind() in JavaScript

Hi there,
In this post, I'm gonna talk about the function methods mentioned in the title. A lot of new JavaScript devs find them difficult to understand, so here I am!

Here's our object for example purposes:

const person = { name: "Aman" }

The function which we want to invoke as object method:

const intro = function(profession, country) {
  return `${this.name} is a ${profession}, who lives in ${country}.`
}
Enter fullscreen mode Exit fullscreen mode

call()

call() is used to invoke a function as method, where first parameter refers to the "this" for the object, remaining parameters acts as regular function parameters.

console.log(intro.call(person, "Developer", "India"));
// Outputs: "Aman is a Developer, who lives in India."
Enter fullscreen mode Exit fullscreen mode

apply()

apply() is similar to call(), only difference is the way function parameters are passed i.e. in an array, instead of comma-separated arguments.

console.log(intro.apply(person, ["Developer", "India"]));
// Outputs: "Aman is a Developer, who lives in India."
Enter fullscreen mode Exit fullscreen mode

bind()

bind() is different compared to call() & apply(). When we pass the "this" of the object as argument, it returns a bound function which we can invoke later.

const boundIntro = intro.bind(person);
console.log(boundIntro("Developer", "India"));
// Outputs: "Aman is a Developer, who lives in India."
Enter fullscreen mode Exit fullscreen mode

Top comments (0)