匿名调用函数的参数计数是否在 Javascript 中可用?

Is a parameter count availabe in Javascript for an anonymous invoked function?

(function (a, b, c) {

  console.log(arguments.length); // 2

} (1, 2) )

当上述函数运行时,该函数可以通过参数对象的长度 属性.

判断它是仅用两个参数调用的

由于函数定义中列出了 a、b 和 c,函数是否还有一种方法可以告诉它需要 3 个参数?

在上面的函数中:

console.log( what?) === 3?

我通读了这个答案Get a function's arity,但它需要函数的引用(例如名称),并且没有回答我关于函数内部的 console.log 的问题。

是的。示例:

function main(a, b, c) {
    console.log(main.length);
}

main(1, 2);    

看到这个Fiddle

你可以name your function expression[1] and use that reference to get the arity of the function via its .length property:

(function iefe(a, b, c) {
    console.log(arguments.length); // 2
    console.log(iefe.length); // 3
}(1, 2));

1:如果你不关心旧的IE bug。如果您这样做并且在草率模式下工作,arguments.callee 可能是更好的选择。当然,您也可以使用标识符泄漏的函数声明或变量赋值,或者 - 因为您总是引用相同的函数 - 使用常量值。