The difference between the call(), apply(), and bind() methods is as follows:
- All three methods utilize “this” argument to the function.
- The apply() and call() methods set this to a function and call the function.
- The bind() method will only set this to a function. It will need to invoke the function separately.
To utilize the call(), apply(), and bind() methods, check out the stated examples discussed below:
The “call()” method invokes the function and attaches “this” value to it. It accepts “this” as a parameter along with a list of arguments. After that, it returns the value provided by the invoked function utilizing the call() method. To do so, we have called the func with the help of the call() method:
console.log(this.num, arg1, arg2);
The call method will invoke the function along with the arguments passed to the function:
The function is called via the “apply()” method, which also binds “this” value to the function. It calls the function with the help of the apply method, which returns the value, and it accepts this value and a single array object as inputs:
In the stated example, the apply method calls the function, and the object is passed to the apply() method.
The “bind()” method creates a new function and binds this value to the function. But there is still a need to call the returned method on its own. In this code snippet, we bind “this” variable for the test function:
Then, call the returning function using the bind method.
Lastly, call the function directly: