While preparing for a javascript interview most of the javascript programmers face challenges to understand the difference between call, apply and bind methods in javascript. They also face a challenge while understanding why this keyword is used differently as compared to other object-oriented languages.
To overcome all the challenges mentioned above we will be talking about the call, apply, and bind methods in depth so that you can understand them. Apart from that we will also discuss the context of this keyword in javascript objects and functions.
Basic rules to know about “this” keyword in javascript:
- this is used always while referring to an object in javascript
- In general “this” keyword refers to an object which calls the function it contains.
- If we are using “this” as a global context then it either refers to a window object or is undefined if it is used in the “strict mode”.
The above example will work fine as long as we use it in this way. So, the output on the screen will be as shown below:
The problem generally comes when we try to borrow a method.
The above code will not work as the “this” keyword will now be assigned to the global context which will neither have the name property nor the designation property. To overcome this challenge we have a special method called as bind.
The bind() Method
In the case mentioned above, we can use the ES5 bind() method of the function.prototype property. Bind() can be generally used by every single function.
Example:
In a general way, we can say that the bind method creates new function where the “this” refers to a parameter in the parenthesis in this case that is userDetails. In this way the bind method enables calling a function with a specified “this” value.
Output:
Now let us see this example by passing a parameter the printDetails function. In this case also we can use the bind method again. Let’s rewrite it.
Example:
Output
Explanation on call() and apply() method
In general, both call() and apply() methods also belong to the function. prototype property. Let us take another example with a slightly different code as mentioned above. In this example, there is a userDetails object without the printDetails function which is located in the global context.
Example
Always note that while using the apply() function the parameter must be placed in an array. The call method is known for accepting both an array of parameters and the parameter itself. The output on the screen will be as mentioned below.
Output
Call apply and bind methods are generally made to make your life easier when you need to set the value of “this”.
Conclusion
- Call, Apply and Bind helps to make your code cleaner.
- Call, Apply and Bind methods are one of the most incredible methods in javascript that are available to all the javascript functions.
- If we are using “this” as a global context then it either refers to a window object or is undefined if it is used in the “strict mode”.