What are call(), apply() and bind() in JavaScript
Amitav Mishra
Posted on November 23, 2020
In JavaScript this
refers to the owner object. If you want to attach some extra properties to a function, then you can do that with these 3 methods and can access that extra property using the this
keyword. Letβs learn in deep about these 3 methods.
The call() method
The call()
method calls a function with a given value and other arguments provided in the function.
const address = {city: 'Sonepur', state: 'Odisha'};
function print(name) {
console.log('Name: ' + name + ', Address: ' + this.city + ', ' + this.state);
}
print.call(address, 'Amitav');
// Name: Amitav, Address: Sonepur, Odisha
Here in the example above, call()
attaches the address object to the print() function and print() function can access this address object using this
.
You can provide any type of value for this
.
function print() {
console.log('Hello ' + this);
}
print.call('World'); // Hello World
print.call(245); // Hello 245
function print() {
console.log(this[0] + ' ' + this[1]);
}
print.call(['Hello', 'World']); // Hello World
The apply() method
This method invokes the function and allows you to pass the arguments as an array.
const address = {city: 'Sonepur', state: 'Odisha'};
function print(name, age) {
console.log(name +', Age: ' + age + ', Address: ' + this.city + ', ' + this.state);
}
print.apply(address, ['Amitav', 24]);
//Amitav, Age: 24, Address: Sonepur, Odisha
Both call()
and apply()
works the same way. The only difference is that call()
expects all parameters to be provided one by one, whereas apply()
allows you to pass in arguments as an array.
The bind() method
This method returns a new function with the value bound to it, which you can use to call the function with the required arguments.
const address = {city: 'Sonepur', state: 'Odisha'};
function print(name, age) {
console.log(name +', Age: ' + age + ', Address: ' + this.city + ', ' + this.state);
}
const bindAddress = print.bind(address);
bindAddress('Amitav', 24);
//Amitav, Age: 24, Address: Sonepur, Odisha
You may also like
- 20 JavaScript Shorthand Techniques that will save your time
- JavaScript Array forEach() method to loop through an Array
- ES6 Destructuring Assignment in JavaScript
Thanks for your time
Find more Web dev blogs on jscurious.com
Posted on November 23, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
July 16, 2022