The apply, call, and bind methods in JavaScript are primarily used to explicitly set the this context for a function's execution.
The apply Method
fn.apply(thisArg, [argumentsArray])
This method modifies the this binding and immediately invokes the function. The first argument specifies the new this context, while the second is an array (or array-like object) containing the arguments to pass to the function.
const person = {
firstName: 'Alice',
yearsOld: 30,
introduce: function(profession, interest) {
console.log(`I am ${this.firstName}, aged ${this.yearsOld}. I work as a ${profession} and enjoy ${interest}.`);
}
};
const anotherPerson = {
firstName: 'Bob',
yearsOld: 25
};
person.introduce.apply(anotherPerson, ['designer', 'hiking']);
The call Method
fn.call(thisArg, arg1, arg2, ...)
Similar to apply, call changes the this context and executes the function immediately. The key difference is in argument passing: call accepts individual arguments after the thisArg, rather than a single array.
const person = {
firstName: 'Alice',
yearsOld: 30,
introduce: function(profession, interest) {
console.log(`I am ${this.firstName}, aged ${this.yearsOld}. I work as a ${profession} and enjoy ${interest}.`);
}
};
const anotherPerson = {
firstName: 'Bob',
yearsOld: 25
};
person.introduce.call(anotherPerson, 'designer', 'hiking');
The bind Method
fn.bind(thisArg, arg1, arg2, ...)
The bind method creates a new functon with a permanently bound this value and, optioanlly, pre-set initial arguments. Unlike call and apply, bind does not invoke the function immediately. It returns a new function that can be called later.
const person = {
firstName: 'Alice',
yearsOld: 30,
introduce: function(profession, interest) {
console.log(`I am ${this.firstName}, aged ${this.yearsOld}. I work as a ${profession} and enjoy ${interest}.`);
}
};
const anotherPerson = {
firstName: 'Bob',
yearsOld: 25
};
const boundFunction = person.introduce.bind(anotherPerson, 'designer', 'hiking');
boundFunction(); // Function is invoked here
Key Differances Between apply, call, and bind
- Argument Passing:
callandbindaccept arguments as a comma-separated list.applyrequires arguments to be provided as a single array. - Execution Timing: Both
callandapplyinvoke the function immediately upon being called.bindreturns a new function with a bound context, delaying execution until the returned function is explicitly called.