传递比函数声明更多的参数是不是很糟糕?

Kyl*_*yle 23 javascript

我有一个功能

function callback(obj){...}
Run Code Online (Sandbox Code Playgroud)

是否可以传入比函数签名中声明的更多的对象?例如这样称呼它:

callback(theObject, extraParam);
Run Code Online (Sandbox Code Playgroud)

我在Firefox上尝试过它并没有出现问题,但是这样做不好吗?

CMS*_*CMS 39

JavaScript允许这样,你可以将任意数量的参数传递给一个函数.

它们可以在arguments对象中访问,该对象是一个类似数组的对象,其数字属性包含调用函数时使用的参数值,该length属性告诉您调用时已使用了多少个参数,以及callee属性是函数本身的引用,例如你可以写:

function sum(/*arg1, arg2, ... , argN  */) { // no arguments defined
  var i, result = 0;
  for (i = 0; i < arguments.length; i++) {
    result += arguments[i];
  }
  return result;
}
sum(1, 2, 3, 4); // 10
Run Code Online (Sandbox Code Playgroud)

arguments对象可能看起来像一个数组,但它是一个普通的对象,继承自Object.prototype,但是如果你想在其上使用Array方法,你可以直接从它调用它们Array.prototype,例如,一个普通的模式来获得一个真正的数组是使用Array slice方法:

function test () {
  var args = Array.prototype.slice.call(arguments);
  return args.join(" ");
}
test("hello", "world"); // "hello world"
Run Code Online (Sandbox Code Playgroud)

此外,您可以使用函数对象的属性知道函数需要多少个参数length:

function test (one, two, three) {
  // ...
}
test.length; // 3
Run Code Online (Sandbox Code Playgroud)