Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to pass 'arguments' to 'apply()'

Tags:

javascript

Suppose I have the following code (completely useless, I know)

function add( a, b, c, d ) {
  alert(a+b+c+d);
}

function proxy() {
    add.apply(window, arguments);
}

proxy(1,2,3,4);

Basically, we know that apply expects an array as the second parameter, but we also know that arguments is not a proper array. The code works as expected, so is it safe to say that I can pass any array-like object as the second parameter in apply()?

The following will also work (in Chrome at least):

function proxy() {
  add.apply(window, {
    0: arguments[0],
    1: arguments[1],
    2: arguments[2],
    3: arguments[3],
    length: 4
  });
}

Update: It seems that my second code block fails in IE<9 while the first one (passing arguments) works. The error is Array or arguments object expected, so we shall conclude that it's always safe to pass arguments, while it's not safe to pass an array-like object in oldIE.

like image 485
David Fregoli Avatar asked May 14 '13 12:05

David Fregoli


1 Answers

From definition of Function.prototype.apply in MDN:

fun.apply(thisArg[, argsArray])

You can also use arguments for the argsArray parameter. arguments is a local variable of a function. It can be used for all unspecified arguments of the called object. Thus, you do not have to know the arguments of the called object when you use the apply method. You can use arguments to pass all the arguments to the called object. The called object is then responsible for handling the arguments.

REF: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply

As the second argument apply accepts "an array like object, specifying the arguments with which function should be called". To my understanding, this array-like object should have the length property for internal iteration, and numerically defined properties (zero-indexed) to access the values.

And the same is confirmed my the spec: http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.4.3, as was kindly pointed out by @Pointy.

like image 151
VisioN Avatar answered Oct 21 '22 01:10

VisioN