All these functions are related to this keyword.
this is used inside function and it refers to the object which calls that function.
In the above example, this is used to refer to the object fruit1. And so, this.quantity is 2 and this.name is ‘Apple’.
What if we have another similiar function, and we need to have the same function getString() for it? Something like the example below.
Should we write getString() function inside every objects? Thats a lot of work, right?
Instead, we can write getString() function once and use it with different objects.
Let’s see how to do this.
According to mozilla ,
call() method calls a function with a given
thisvalue and arguments provided individually.
So what call() method does is, it helps us to invoke a function where we can specify the context in which it is invoked.
Here the context of getString() function is set to fruit1 first, and this points to the fruit1. Hence the output is ‘2 Apple remaining’.
Second time, the getString() function is set to fruit2 and the output is “4 Mango remaining”.
There is more to the call() function, after the first parameter as context, we can also pass other parameters to it.
So , we can pass the parameters one by one to the call function and it would work. But what if we have many parameters to pass. Wouldn’t it be better if we would pass the parameters at once. So to handle such case, we have apply() function
To avoid having too many parameters inside call function. We have another approach i.e using apply( ) function.
Here we can pass all the parameters as an array.
And it would work. That’s the only difference between call( ) & apply( )
Let’s see an example.
As we have seen , call( ) and apply( ) are used to invoke the function while providing the context to the function.
Bind( ) is same as call( ) except that instead of invoking the function , bind( ) is used to return a function while providing the context to that function.
This can be very useful where we want to create a new function and use it later. Its good to know about these functions, as these can be used to write better code.
Hope this helps you clear your concepts about these functions. Please share if you like the blog post.
Have any thoughts about this post or this topic? Please reach out in the comments.