What is the difference between call()
, apply()
and bind()
?
In JavaScript, call
, apply
, and bind
are three methods that allow us to manipulate function behavior and pass arguments to functions. While they seem similar, each has its own unique use cases and usage scenarios.
call()
The call()
method calls a function with a given this
value, arguments, and returns the result of the called function.
It's primarily used when you need to execute a function immediately after setting a specific this
context.
Syntax
function call(thisArg, arg1, arg2, ...)
Example
const add = function(a, b) {
return a + b;
};
// Using call()
// - Output: "3"
console.log(
add.call({ name: 'John' }, 1, 2)
);
apply()
The apply()
method is similar to call()
, but it accepts an array of arguments instead of individual arguments.
Signature: function apply(thisArg, argsArray)
Example:
const add = function(a, b) {
return a + b;
};
// Using apply()
console.log(add.apply({ name: 'John' }, [1, 2])); // Output: "3"
In this example, apply
sets the same this
context as call()
and passes an array [1, 2]
to the add
function.
bind()
The bind()
method creates a new function with a given this value in its this
property, without immediately executing it.
Signature: function bind(thisArg, arg1, arg2, ...
Example:
const add = function(a, b) {
return a + b;
};
// Using bind()
const boundAdd = add.bind({ name: 'John' });
console.log(boundAdd(1, 2)); // Output: "3"
In this example, bind
creates a new function boundAdd
with the this
context set to { name: 'John' }
. When we call boundAdd(1, 2)
, it returns "3"
as expected.
In Summary
- Use
call
when you need to execute a function immediately with a specificthis
context. - Use
apply
when you have an array of arguments and want to execute the function with a specificthis
context. - Use
bind
when you want to create a new function with a specificthis
context without executing it immediately.
By understanding these differences, you'll be able to effectively use call
, apply
, and bind
in your JavaScript development workflow.