The main difference is that
apply
lets you invoke the function with arguments as an array; call
requires the parameters be listed explicitly.
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.
No comments:
Post a Comment