What is the difference between using call
and apply
to invoke a function?
var func = function() {
alert(\'hello!\');
};
>
From the MDN docs on Function.prototype.apply() :
The apply() method calls a function with a given
this
value and arguments provided as an array (or an array-like object).Syntax
fun.apply(thisArg, [argsArray])
From the MDN docs on Function.prototype.call() :
The call() method calls a function with a given
this
value and arguments provided individually.Syntax
fun.call(thisArg[, arg1[, arg2[, ...]]])
From Function.apply and Function.call in JavaScript :
The apply() method is identical to call(), except apply() requires an array as the second parameter. The array represents the arguments for the target method.
var doSomething = function() {
var arr = [];
for(i in arguments) {
if(typeof this[arguments[i]] !== 'undefined') {
arr.push(this[arguments[i]]);
}
}
return arr;
}
var output = function(position, obj) {
document.body.innerHTML += 'output ' + position + '
' + JSON.stringify(obj) + '\n
\n
';
}
output(1, doSomething(
'one',
'two',
'two',
'one'
));
output(2, doSomething.apply({one : 'Steven', two : 'Jane'}, [
'one',
'two',
'two',
'one'
]));
output(3, doSomething.call({one : 'Steven', two : 'Jane'},
'one',
'two',
'two',
'one'
));
See also this Fiddle.