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?
We can differentiate call and apply methods as below
CALL : A function with argument provide individually. If you know the arguments to be passed or there are no argument to pass you can use call.
APPLY : Call a function with argument provided as an array. You can use apply if you don't know how many argument are going to pass to the function.
There is a advantage of using apply over call, we don't need to change the number of argument only we can change a array that is passed.
There is not big difference in performance. But we can say call is bit faster as compare to apply because an array need to evaluate in apply method.
Here's a good mnemonic. Apply uses Arrays and Always takes one or two Arguments. When you use Call you have to Count the number of arguments.
To answer the part about when to use each function, use
apply
if you don't know the number of arguments you will be passing, or if they are already in an array or array-like object (like thearguments
object to forward your own arguments. Usecall
otherwise, since there's no need to wrap the arguments in an array.When I'm not passing any arguments (like your example), I prefer
call
since I'm calling the function.apply
would imply you are applying the function to the (non-existent) arguments.There shouldn't be any performance differences, except maybe if you use
apply
and wrap the arguments in an array (e.g.f.apply(thisObject, [a, b, c])
instead off.call(thisObject, a, b, c)
). I haven't tested it, so there could be differences, but it would be very browser specific. It's likely thatcall
is faster if you don't already have the arguments in an array andapply
is faster if you do.The main difference is, using call, we can change the scope and pass arguments as normal, but apply lets you call it using arguments as an Array (pass them as array). But in terms of what they to do in your code, they are pretty similar.
So as you see, there is not a big difference, but still there are cases we prefer using call() or apply(). For example, look at the code below, which finding smallest and largest number in an array from MDN, using the apply method:
So the main difference is just the way we passing the arguments:
Call:
Apply:
Call() takes comma-separated arguments, ex:
.call(scope, arg1, arg2, arg3)
and apply() takes an array of arguments, ex:
.apply(scope, [arg1, arg2, arg3])
here are few more usage examples: http://blog.i-evaluation.com/2012/08/15/javascript-call-and-apply/
The difference is that
call()
takes the function arguments separately, andapply()
takes the function arguments in an array.