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?
Here's a small-ish post, I wrote on this:
http://sizeableidea.com/call-versus-apply-javascript/
Even though
call
andapply
achive the same thing, I think there is atleast one place where you cannot usecall
but can only useapply
. That is when you want to support inheritance and want to call the constructor.Here is a function allows you to create classes which also supports creating classes by extending other classes.
The difference is that
apply
lets you invoke the function witharguments
as an array;call
requires the parameters be listed explicitly. A useful mnemonic is "A for array and C for comma."See MDN's documentation on apply and call.
Pseudo syntax:
theFunction.apply(valueForThis, arrayOfArgs)
theFunction.call(valueForThis, arg1, arg2, ...)
There is also, as of ES6, the possibility to
spread
the array for use with thecall
function, you can see the compatibilities here.Sample code:
K. Scott Allen has a nice writeup on the matter.
Basically, they differ on how they handle function arguments.
So:
Another example with Call, Apply and Bind. The difference between Call and Apply is evident, but Bind works like this:
}
While this is an old topic, I just wanted to point out that .call is slightly faster than .apply. I can't tell you exactly why.
See jsPerf, http://jsperf.com/test-call-vs-apply/3
[
UPDATE!
]Douglas Crockford mentions briefly the difference between the two, which may help explain the performance difference... http://youtu.be/ya4UHuXNygM?t=15m52s
Apply takes an array of arguments, while Call takes zero or more individual parameters! Ah hah!
.apply(this, [...])
.call(this, param1, param2, param3, param4...)