What is difference between bind, call, and apply in Javascript?
In Javascript, all function objects automatically have the methods “bind”, “call”, and “apply”. What is the difference between them?
Javascript bind method
First let’s look at the bind method by considering the Javascript here which will output “Hello Doggie” to the browser console…
We have a function “greetPet” which uses the “this” keyword. We can affect what the “this” points to by using the “bind” method of the function. In line 21, we pass the object “pet” into the bind method. So the function’s this keyword will point to the “pet” object. The bind method makes a copy of the function, which we store in greetDog. This new greetDog function is a copy of the greetPet function but with the “this” keyword binded to “pet” object.
So when we call greetDog(), it console out the petname of “pet”.
Javascript call method
Now we have changed our example in line 21 to use the “call” method of the greetPet function …
Like the bind method, we pass to it the object which we want the “this” keyword to point to. But unlike bind, it executes the function immediately instead of making a copy of it for later to be called.
And suppose our greetPet function had parameters such as a boolean indicating whether to use formal greeting or not. For example, like this …
You would just add these parameter values to the end of the call method like shown above.
Javascript apply method
The “apply” method is the same as the call method, but the parameters are in an array instead. For example…
This may be useful if the function has a lot of parameters that you want to build up in the array. Here our array is only one element.