Net-informations.com
SiteMap  | About    

Difference between .call and .apply

In JavaScript, everything are objects , even Functions, and every objects has their properties and methods. Both .apply and .call are methods of Function object. Still, many people get confused with these two functions in JavaScript.

Basically, they differ on how they handle function arguments . Both functions allow you to control the meaning of 'this' inside the called function, but the difference is in how arguments are passed to the function. The apply() method is identical to call() , except apply() requires an array as the second parameter. The array represents the arguments for the target method.

.call()

It calls a function with given values and arguments provided individually

example

.apply()

It calls a function with given values and arguments provided as an array or array object.

example

The first argument, in both cases, is the object reference that will represent 'this' inside the called function. So that's the difference between call and apply. Both can be called on functions, which they run in the context of the first argument. In call the subsequent arguments are passed in to the function as they are, while apply expects the second argument to be an array that it unpacks as arguments for the called function. Let's see an example which will make it clearer.

example

output









net-informations.com (C) 2018    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.