Javascript call apply bind

From Logic Wiki
Jump to: navigation, search


.call()

This method is used to call a function with given value & arguments. Know that when we invoke a function in JavaScript like functionName(), under the hood, it actually works like functionName.call(). Here, we’ll be using .call() method to borrow the salaryHike() method from employeeOne & use it for employeeTwo. Sounds exciting? Let’s see how we can do it

Call1.png

Here, we are invoking the salaryHike() method of employeeOne & using .call() method to borrow this method & use it for employeeTwo object.


Now, take a look at the salaryHike() method inside object employeeOne, you’ll see that we have set a static value of 10000 whenever this function is called. Let’s change that & make it a dynamic one, so that we can give different amount of hikes to different employees on the basis of their performance.

Call2.png

Here, you’ll see that, in the .call() method, we can set arguments as well, such that, we are setting the value of 20000 as an argument. Apart from that, the salaryHike() will receive hike as a parameter, which can be further used to increment the salary.

.apply()

Now, let’s try to implement the same example by replacing .call() method with .apply().

Apply1.png

We have not changed anything, except for replacing .call() with .apply(). Now, let’s check the output -

Apply2.png

Here, as you can see, we receive an error. It has occurred because we can not set the arguments in .apply() method like we did in the .call() method. In .apply() method, the arguments need to be passed within an array, like so -

Apply3.png

.bind()

When we use .bind() method, it returns a function.

Bind1.png

Here, we are assigning the returned function by .bind() method to variable hikeEmployeeTwo. This variable now acts as a function which is further invoked in the next line.