What is the difference between using call
and apply
to invoke a function?
var func = function() {
alert('hello!');
};
func.apply();
vs func.call();
Are there performance differences between the two aforementioned methods? When is it best to use call
over apply
and vice versa?
Call and apply both are used to force the
this
value when a function is executed. The only difference is thatcall
takesn+1
arguments where 1 isthis
and'n' arguments
.apply
takes only two arguments, one isthis
the other is argument array.The advantage I see in
apply
overcall
is that we can easily delegate a function call to other function without much effort;Observe how easily we delegated
hello
tosayHello
usingapply
, but withcall
this is very difficult to achieve.Summary:
Both
call()
andapply()
are methods which are located onFunction.prototype
. Therefore they are available on every function object via the prototype chain. Bothcall()
andapply()
can execute a function with a specified value of thethis
.The main difference between
call()
andapply()
is the way you have to pass in arguments into it. In bothcall()
andapply()
you pass as a first argument the object you want to be the value asthis
. The other arguments differ in the following way:call()
you have to put in the arguments normally (starting from the second argument)apply()
you have to pass in array of arguments.Example:
Why would I need to use these functions?
The
this
value can be tricky sometimes in javascript. The value ofthis
determined when a function is executed not when a function is defined. If our function is dependend on a rightthis
binding we can usecall()
andapply()
to enforce this behaviour. For example: