In JavaScript, call
, apply
, and bind
are three methods that allow you to control the execution context of a function. They are used to manipulate how a function is invoked and what value is assigned to the this
keyword within the function. Here’s a brief explanation of each method:
1. call
: The call
method allows you to call a function with a specified this
value and additional arguments provided individually (comma-separated). The syntax is as follows:
functionName.call(thisArg, arg1, arg2, ...);
functionName
: The function you want to call.thisArg
: The value to be passed as thethis
value within the function.arg1, arg2, ...
: Optional arguments to be passed to the function individually.
2. apply
: The apply
method is similar to call
, but it accepts the function’s arguments as an array or an array-like object. The syntax is as follows:
functionName.apply(thisArg, [arg1, arg2, ...]);
functionName
: The function you want to call.thisArg
: The value to be passed as thethis
value within the function.[arg1, arg2, ...]
: An array or an array-like object containing the arguments to be passed to the function.
3. bind
: The bind
method creates a new function that, when called, has its this
value set to the provided value. It also allows you to partially apply arguments to a function, creating a new function with some arguments already set. The syntax is as follows:
let newFunction = functionName.bind(thisArg, arg1, arg2, ...);
functionName
: The function you want to bind.thisArg
: The value to be passed as thethis
value within the function when the new function is called.arg1, arg2, ...
: Optional arguments to be partially applied to the function.
Call apply bind in JavaScript example
Simple example code.
const person = {
name: 'John',
sayHello: function(greeting) {
console.log(`${greeting}, ${this.name}!`);
}
};
const anotherPerson = {
name: 'Alice'
};
person.sayHello.call(anotherPerson, 'Hi');
person.sayHello.apply(anotherPerson, ['Hello']);
const boundFunction = person.sayHello.bind(anotherPerson, 'Hey');
boundFunction();
Output:
In the example above, call
and apply
are used to invoke the sayHello
function with a different this
value (anotherPerson
). On the other hand, bind
is used to create a new function boundFunction
, which is permanently bound to anotherPerson
as its this
value and has the argument 'Hey'
partially applied.
Comment if you have any doubts or suggestions on this JS bind topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version