JavaScript: bind(), call() and apply() method
Sometimes, working with JavaScript, this
Keyword is quite confusing and we often tend to make mistakes while using it. There are few simple rules that we should consider while referring to this
:
- “
this
” always refer to the object. - “
this
” — In the global context, will always refer to the window object. But if we are in strict mode, this will be undefined. - “
this
” refers to the object which calls the function.
You can get a detailed context here: this.
bind() Method:
To understand the bind() method, let’s have a look at the below code:
Works fine. As expected.
Now, look at the below code:
Here, the output will be ’’
.
The reason is, in the first block, the default binding of this occurs and it directly refers to the user object. However, in the second case, the binding is lost. To handle such cases, we require the bind() method.
With the help of the bind() method, we can set the context of this to a particular object. This will help in using the different variables for calling the bound functions.
Bind() method creates the new function, where this
refers to the parameter within the parenthesis, in this way, it helps in calling a function with specific this
value.
Using bind() in the second example is:
call() and apply() Method:
The call() method, calls a function with a given this
value and arguments provided individually. Let’s explore it more -
It has syntax as below:
obj.objMethod.call( objInstance, arguments )
Consider the below code,
call() and apply() methods serve the same purpose, however, there is a difference in the way how parameters are passed to them.
apply() function will accept the parameters as an array, whereas call() will require individual parameters.
Re-writing the above function using apply:
Now, while working, sometimes, you will come across the scenarios where null is passed in the call() and apply() method. Let’s have a look at the below code to understand this:
So, what does this exactly mean to have null as a parameter?
This means we are calling the function, without providing any object for “this
”. When there is no value you wish to specify for the this
pointer inside the function and the function we are calling say sumOfNumbers()
here, is not expecting any value of this
.
Hope this helps in getting the basic idea of bind(), apply() and call().
Happy coding :)