What is call, apply and bind in JavaScript?
In JavaScript, call
, apply
, and bind
are methods that allow you to invoke a function with a specified this
value and arguments.
call
method: The call
method allows you to invoke a function and specify the this
value for the function. The call
method takes two or more arguments. The first argument is the value you want to use as the this
value, and the rest of the arguments are passed to the function as individual parameters.
let person = {
name: 'John Doe',
greet: function(prefix) {
console.log(prefix + ' ' + this.name);
}
};
let friend = { name: 'Jane Doe' };
person.greet.call(friend, 'Hello'); // logs 'Hello Jane Doe'
apply
method: The apply
method is similar to the call
method, but it takes an array of arguments instead of individual parameters. The first argument is still the value you want to use as the this
value.
let person = {
name: 'John Doe',
greet: function(prefix) {
console.log(prefix + ' ' + this.name);
}
};
let friend = { name: 'Jane Doe' };
person.greet.apply(friend, ['Hello']); // logs 'Hello Jane Doe'
bind
method: The bind
method creates a new function with a specified this
value and arguments, and returns the new function. When the new function is invoked, it will use the this
value and arguments that were specified in the bind
method.
let person = {
name: 'John Doe',
greet: function(prefix) {
console.log(prefix + ' ' + this.name);
}
};
let friend = { name: 'Jane Doe' };
let greetFriend = person.greet.bind(friend, 'Hello');
greetFriend(); // logs 'Hello Jane Doe'
In summary, call
, apply
, and bind
are useful for controlling the this
value of a function, and for passing arguments to a function. The main difference between these methods is the way they pass arguments to the function. The call
and apply
methods invoke the function immediately, while the bind
method returns a new function that can be invoked later.