Difference between .call and .apply [duplicate]
Is there a simple way to passing all arguments from one function to another and sending this
also.
I have tried this: http://jsfiddle.net/v92Xr/
var f1 = function() 开发者_如何学C{
f2.call(this, arguments);
};
var f2 = function() {
console.log(arguments);
};
f1("abc", "def", "hij");
but it leaves me all the arguments from f1 is stacked in f2 arguments 0:
f2->arguments[0] == f1->arguments
Ok and when i run the apply
method instead it works: http://jsfiddle.net/v92Xr/1/
var f1 = function() {
f2.apply(this, arguments);
};
var f2 = function() {
console.log(arguments);
};
f1("abc", "def", "hij");
So can anyone please tell me what's the difference between call
and apply
is?
I think you've just discovered the difference yourself.
call
is almost identical to way you would normally call a function except there is an extra parameter at the start of the parameter list where you place the reference for the this
object.
apply
also has the first parameter as the this
object but the second parameter is expected to be an array. This array is used to supply all the arguments that the called function is expecting. Element 0 maps to the first argument in the functions argument list, element 1 to the second and so on.
call MDN: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call
Calls a function with a given this value and arguments provided individually.
fun.call(thisArg[, arg1[, arg2[, ...]]])
apply MDN: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply
Calls a function with a given this value and arguments provided as an array.
fun.apply(thisArg[, argsArray])
精彩评论