Call, Apply, and Bind in JavaScript

Call, Apply, and Bind in JavaScript

In JavaScript, Call, Apply, and Bind are three methods that can be used to manipulate the context and arguments of a function.

In other words, we can control the value of the ‘this’ from the parent context. This can make methods reusable.

Let’s see the Call method first.

Let’s have a function that prints the first and last names from the ‘this’, which means the surrounding context.

const person = {
  firstName: "Nishant",
  lastName: "Kumar",
};

function greet(age) {
  console.log(`${this.firstName} ${this.lastName} is ${age} years old!`);
}
}        

We can use the Call method to pass dynamic values, which the function could use as the values. The Call method takes two arguments, first is the context or the object that we want to set as this within the function. and second is the additional arguments, separated by a comma.

greet.call({ firstName: "Jesse", lastName: "Custer" });
greet.call({ firstName: "Cassidy", lastName: "The Vampire" }, 500);        

The Apply method is almost as same as the Call method, but the difference is how we pass arguments. The Call method took args separated by a comma, but the Apply method takes it as an array.

greet.call({ firstName: "Cassidy", lastName: "The Vampire" }, [500]);        

The third method is the Bind method. 

The Bind method binds the function it is called upon, with the object which will become the ‘this’ context. It then returns us a copy of the method that we can use later.

In other words, Bind will return us a function that we have to invoke manually. 

const person = {
  firstName: "Saint of",
  lastName: "Killers",
};

function greet(age) {
  console.log(`${this.firstName} ${this.lastName} is ${age} years old!`);
}

let greetAgain = greet.bind(person, 300);
greetAgain();        

This is Call, Apply, and Bind. 

Thanks for reading, and I will see you in the next one.

Follow me on Medium: https://nishants440.medium.com/

Join me on Discord: https://discord.gg/T7aH8kPp

To view or add a comment, sign in

Others also viewed

Explore content categories