call, apply and bind.
Three methods every JavaScript function has. call and apply run a function with a this you choose; bind gives you a new function to run later.
Let's take one of the most asked interview questions.
First, call and apply are almost the same. The only difference is how you pass the arguments.
- call and apply run a function straight away, with the object you give them as
this. - bind creates a new function with a given
thisand returns it without running it.
Starting with a method on an object
const person1 = {
firstName: "Himanshu",
lastName: "Satija",
fullName() {
return this.firstName + " " + this.lastName;
},
};
person1.fullName(); // "Himanshu Satija"Now a second object of the same kind.
const person2 = {
firstName: "Ada",
lastName: "Lovelace",
fullName() {
return this.firstName + " " + this.lastName;
},
};
person2.fullName(); // "Ada Lovelace"Imagine thousands of objects like this. Each one carries its own copy of the same function, which wastes memory and time. call, apply and bind let us write the function once and use it for any object.
call
Change the objects a little. The first keeps the function, now with two arguments. The second has only data.
const person1 = {
firstName: "Himanshu",
lastName: "Satija",
fullName(city, age) {
return this.firstName + " " + this.lastName + ", " + city + ", " + age;
},
};
const person2 = {
firstName: "Ada",
lastName: "Lovelace",
};To run fullName for person2, pass person2 as the first argument to call. The rest are the function's own arguments.
person1.fullName.call(person2, "London", 36); // "Ada Lovelace, London, 36"apply
apply does the same thing. The only difference is that the arguments go in an array.
person1.fullName.apply(person2, ["London", 36]); // "Ada Lovelace, London, 36"bind
bind does not run anything. It returns a new function with this fixed, and you call that function when you want the result.
const fullNameOfPerson2 = person1.fullName.bind(person2);
fullNameOfPerson2("London", 36); // "Ada Lovelace, London, 36"Arguments can be given to bind as well, or split between bind and the later call.
const inLondon = person1.fullName.bind(person2, "London");
inLondon(36); // "Ada Lovelace, London, 36"Taking the function out of the object
The function does not have to live on an object at all.
const fullName = function (city, age) {
return this.firstName + " " + this.lastName + ", " + city + ", " + age;
};
const ada = { firstName: "Ada", lastName: "Lovelace" };
const grace = { firstName: "Grace", lastName: "Hopper" };
fullName.call(ada, "London", 36); // "Ada Lovelace, London, 36"
fullName.apply(grace, ["New York", 37]); // "Grace Hopper, New York, 37"These built-in methods exist on every JavaScript function. Even if you rarely reach for them in day-to-day work, you will run into them often when reading other people's code.