简体   繁体   中英

What is the difference between these two ways to leverage the arguments object in a JavaScript function?

In the documentation for the Array.prototype.slice method it says:

Binding can be done with the .call function of Function.prototype and it can also be reduced using [].slice.call(arguments) instead of Array.prototype.slice.call.

function getArgs() {
  var args = [].slice.call(arguments);
  return args;
}
getArgs(1,2,3); // returns [1, 2, 3]

function getArgs2() {
  var args = Array.prototype.slice.call(arguments);
  return args;
}
getArgs2(1,2,3); // returns [1, 2, 3]

Essentially what is the difference? Is there a performance benefit using one over the other method? Or is the former just easier to type out?

Those both do the same thing, which is to call the array .slice() method. The first way gets at the function via the implicit prototype lookup from a new empty array, and the other goes explicitly to the Array.prototype object. There is probably a performance difference but it's not significant or relevant, since both ways throw away a lot of performance anyway: passing the arguments object out of a function is likely to make the runtime system give up on optimizing the function.

To avoid that performance penalty, a simple local for loop should be used instead:

function foo() {
  var args = [];
  for (var i = 0; i < arguments.length; ++i) args[i] = arguments[i];
  // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM