In JavaScript, call(), apply(), and bind() are methods used to manipulate the way a function is invoked. They allow you to set the context (the value of this) and pass arguments to a function.
call() Method in JavaScript
The call() method is used to invoke a function with a specified value and individual arguments provided as separate parameters.
Syntax
function.call(thisArg, arg1, arg2, ...)
Example
function greet(name) {
console.log(`Hello, ${name}! I am ${this.title}`);
}
const context = { title: 'Mr. Jithu' };
greet.call(context, 'C# Corner');
Output
apply() Method in JavaScript
The apply() method is similar to call(), but it accepts arguments as an array.
Syntax
function.apply(thisArg, [arg1, arg2, ...])
Example
function greet(name) {
console.log(`Hello, ${name}! I am ${this.title}`);
}
const context = { title: 'Mr. Jithu' };
greet.apply(context, ['C# Corner']);
Output
bind() Method in JavaScript
The bind() method creates a new function with the same body as the original function but a fixed value and optionally, pre-specified arguments.
Syntax
function.bind(thisArg, arg1, arg2, ...)
Example
function greet(name) {
console.log(`Hello, ${name}! I am ${this.title}`);
}
const context = { title: 'Mr.Jithu' };
const boundGreet = greet.bind(context, 'C# Corner');
boundGreet();
Output
call() and apply() are used for immediate invocation, while bind() is often used to create a new function that can be invoked later.
Note. In modern JavaScript, arrow functions do not have their own, so these methods are less commonly used with arrow functions. They are more relevant for regular functions where the value of this depends on how the function is called.
Example for the complete call(), bind() and apply() for clear understanding
var pokemon = {
firstname: 'Pika',
lastname: 'Chu ',
getPokeName: function() {
var fullname = this.firstname + ' ' + this.lastname;
return fullname;
}
};
var pokemonName = function(snack, hobby) {
console.log(this.getPokeName() + ' loves ' + snack + ' and ' + hobby);
}
var logPokemonname= pokemonName.bind(pokemon);
logPokemonname('sushi', 'algorithms'); // called as a function with arguments
pokemonName.call(pokemon,'sushi', 'algorithms'); // object has passed along with the arguments
pokemonName.apply(pokemon,['sushi', 'algorithms']); // object has passed to the function with a set of arrays.
Output for the above code snippet is as follows.