If you where been programming in JavaScript for a while, you probably come across one of the following “call”, “apply” or “bind” functions. At first glance, they can look like something complex, but it is an exceptional developer ally when this expression is added to the code.
Call
The call() method is a function capable of changing this value. By default, the first parameter it receives is this value, and the other parameters are from the function that invokes the Call method.
In the following example, we’ll create an object and a function that references this without having this referenced in its scope.
As the print function and the article object do not have any connection, print will print undefined, as it looks for this.title and this.language in the global object and does not find them.
Note: Attempting this in strict mode would result in Uncaught TypeError: Cannot read property ‘title’ of undefined.
In this scenario, we can use the call to specify this context of the article object in the function.
Apply
Apply works the same as the Call method, but its second parameter receives a function parameters Array, and the first parameter continues to receive the value assigned to this. Let’s see a new example, but now using apply:
Bind
Bind, on the other hand, works differently from call and apply, instead of executing a function, it returns a new function. Its first parameter continues to receive the value assigned to this, and the other arguments will be the parameters that will define the values assigned to the first function.
Let’s see an example below:
In line 7 with the bind(5) method, we define the value of this and the function returned in bindResultFunction we assigned the values to the parameters of the first function – sumNumbers, as the secondNumber parameter initialized with 0, the final result was 10.
Now let’s see a new example defining two values for the function parameters:
Arrow Functions
Arrow Functions don’t have a scope for this. Instead, they move on to the next level of execution.
As in the example below:
However, in determined scenarios, it can be useful to use arrow functions while this references the external context. For these scenarios, we can use a constructor to execute the arrow function.
Conclusion
In this article, we learned the different values that this can receive using the call, bind and apply methods.
Leave a comment