Understanding Call, Bind and Apply Methods in JavaScript
In this article, we will learn about Call, Bind and Apply Methods in JavaScript.
In JavaScript, the value of this depends on how a function is called.
Let’s look at some examples to demonstrate the behavior of this in JavaScript.
const users = {
firstName: 'John',
lastName: 'Doe',
getName: function() {
console.log(this.firstName + ' ' + this.lastName);
}
};
users.getName();//John Doe
Above, we executed the getName() method using the users object, so the this keyword inside the method refers to the users object.
Let’s write the below snippet at the end of the above code.
const printFullName = users.getName;
printFullName();
It will prints:
undefined undefined
But Why??
Here, we are storing a reference of users.getName
to printFullName
variable. After that, we are calling it without an object reference, so this
will now refer to the window (global) object or undefined (in strict mode).
If the script is in strict mode, this refers to undefined, therefore console.log() will produce an error.
So it's clear that, the this keyword inside a function refers to different objects depending on how the function is called and sometimes we may unintentionally lose reference to the this variable. So How can we stop it from happening, then?
Let's see,
Use of Call, Bind and Apply Methods:
In JavaScript, functions are a special kind of object, So they have access to some methods and properties like call(), bind(), and apply().
Call()
Call() is a predefined javascript method, which is used to write methods for different objects.
It calls the method, taking the owner object as an argument.
The keyword this refers to the “owner” of the function or the object it belongs to
WIth call(), an object can use a method belonging to another object
The call method sets the this inside the function and immediately executes that function.
The difference between call() and bind() is that the call() sets the this keyword and executes the function immediately and it does not create a new copy of the function, while the bind() creates a copy of that function and sets the this keyword.
Syntax:
function.call(thisArg, arg1, agr2, ...)
For example,
function greeting() {
console.log(`Hi, I am ${this.name} and I am ${this.age} years old`);
}
const john = {
name: 'John',
age: 24,
};
const jane = {
name: 'Jane',
age: 22,
};
// Hi, I am John and I am 24 years old
greeting.call(john);
// Hi, I am Jane and I am 22 years old
greeting.call(jane);
Above example is similar to the bind() example except that call() does not create a new function. We are directly setting the this keyword using call().
Call() also accepts a comma-separated list of arguments. The general syntax for this is function.call(this, arg1, arg2, ...)
function greet(greeting) {
console.log(`${greeting}, I am ${this.name} and I am ${this.age} years old`);
}
const john = {
name: 'John',
age: 24,
};
const jane = {
name: 'Jane',
age: 22,
};
// Hi, I am John and I am 24 years old
greet.call(john, 'Hi');
// Hi, I am Jane and I am 22 years old
greet.call(jane, 'Hello');
The main differences between bind() and call():
- Call() method accepts additional parameters as well
- Call() method Executes the function it was called upon right away.
- The call() method does not make a copy of the function while it is being called.
Apply()
The Apply method is smilar to call method
The call() methpd takes arguments seprately
THe apply method takes arguments as an array
With the apply() method, you can write a method that can be used on different objects. The JavaScript apply() method is similar to the call() method.
The apply() method Works same as call but only diffrence is that apply does not recive a list of comma seprated arguments after the this keyword, but need to pass an array of data
Syntax:
function.apply(thisArg, [argumentsArr])
For Example,
function greet(greeting, lang) {
console.log(lang);
console.log(`${greeting}, I am ${this.name} and I am ${this.age} years old`);
}
const john = {
name: 'John',
age: 24,
};
const jane = {
name: 'Jane',
age: 22,
};
// Hi, I am John and I am 24 years old
greet.apply(john, ['Hi', 'en']);
// Hi, I am Jane and I am 22 years old
greet.apply(jane, ['Hola', 'es']);
In Morden, javascipt apply method is not used anymore because now we acatauly have a better of doing the exact same thing using spread operator as below:
book.call(swiss, ...flightData);
Bind()
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
By this method,we can build an object to a common function,so that the function gives diffrent result when its need
The bind method creates a new function and sets the this keyword to the specified object.
Syntax:
function.bind(thisArg, optionalArguments)
For example:
Let’s suppose we have two person objects.
const john = {
name: 'John',
age: 24,
};
const jane = {
name: 'Jane',
age: 22,
};
Let’s add a greeting function:
function greeting() {
console.log(`Hi, I am ${this.name} and I am ${this.age} years old`);
}
We can use the bind method on the greeting function to bind the this keyword to john and jane objects. For example:
const greetingJohn = greeting.bind(john);
// Hi, I am John and I am 24 years old
greetingJohn();
const greetingJane = greeting.bind(jane);
// Hi, I am Jane and I am 22 years old
greetingJane();
Here greeting.bind(john) creates a new function with this set to john object, which we then assign to greetingJohn variable. Similarly for greetingJane.
Bind() with arguments
We can also pass extra arguments to the bind method. The general syntax for this is function.bind(this, arg1, arg2, ...). For example:
function greeting(lang) {
console.log(`${lang}: I am ${this.name}`);
}
const john = {
name: 'John'
};
const jane = {
name: 'Jane'
};
const greetingJohn = greeting.bind(john, 'en');
greetingJohn();
const greetingJane = greeting.bind(jane, 'es');
greetingJane();
In the above example, the bind method creates a new function with certain parameters predefined (lang in this case) and this keyword set to the john and jane objects.
We can also create bind with specifc property like this:
const bookEW23 = book.bind(eurowings, 23);
//Here just need to pass remaining
bookEW23('Jonas Schmedtmann');
bookEW23('Martha Cooper');
Basically we specifying parts of the arguments beforehand is actually a common pattern called partial application.
So essentailly,partial application means that a part of the arguments of the original funtion are already applied,means already set.
Bind with With Event Listeners
In event handler function,this keyword always points to the element on which that handler is attached to.
So we should use bind here to pass this keyword because call is used to call the method while bind returns the function
lufthansa.planes = 300;
lufthansa.buyPlane = function () {
console.log(this);
this.planes++;
console.log(this.planes);
};
document.querySelector('.buy').addEventListener('click', lufthansa.buyPlane.bind(lufthansa));
Preset parameters with Bind()
We can also preset parameters in bind method, same as below:
const addTax = (rate, value) => value + value * rate;
console.log(addTax(0.1, 200));
const addVAT = addTax.bind(null, 0.23);
//Similar to
//addVAT= value=>value+value *0.23;
console.log(addVAT(100));
console.log(addVAT(23));
Conclusion:
Do let me know If you face any difficulties please feel free to comment below we love to help you.
If you have any feedback suggestion then please inform us by commenting.
Don’t forget to share this tutorial with your friends on Facebook and Twitter