Monday, March 10, 2014

what is the difference between the call and apply in jquery ?

The main difference is that apply lets you invoke the function with arguments as an array; 
callrequires the parameters be listed explicitly.
See here and here.
Pseudo syntax:
theFunction.apply(valueForThis, arrayOfArgs)
theFunction.call(valueForThis, arg1, arg2, ...)
Sample code:
function theFunction(name, profession) {
    alert("My name is " + name + " and I am a " + profession + ".");
}
theFunction("John", "fireman");
theFunction.apply(undefined, ["Susan", "school teacher"]);
theFunction.call(undefined, "Claude", "mathematician");
Note: the second parameter of apply() and call() is optional, not required. 

Note:
Call() takes comma-separated arguments, ex:
.call(scope, arg1, arg2, arg3)
and apply() takes an array of arguments, ex:
.apply(scope, [arg1, arg2, arg3])
The main difference is that apply() lets you invoke the function with arguments as an array; call() requires the parameters be listed explicitly.
function foo(a, b, c) {}
var bar = {};
foo.apply(bar, [1, 2, 3]); // array will expand to the below
foo.call(bar, 1, 2, 3); // results in a = 1, b = 2, c = 3

This is a very common Javascript question that confuses a lot of people (including me). You can use both function.call() and function.apply() in Javascript to execute a function but what’s the difference?
Let’s look at the documentation of call() and apply() first. According to the documentation, .call() means :-
Calls a function with a given this value and arguments provided individually.
and .apply() means :-
Calls a function with a given this value and arguments provided as an array (or an array like object).
The main difference is the apply() takes arguments as an array and call() takes arguments as comma separated list. e.g. if you were to use apply(), your code would look like this :-
1
myfunction.apply(valueForThis, [arrayOfArgs])
Whereas, if you were to use call(), your code would look like this :-
1
myfunction.call(valueForThis, arg1, arg2, ...)

No comments:

Post a Comment