[英]Is a parameter count availabe in Javascript for an anonymous invoked function?
(function (a, b, c) {
console.log(arguments.length); // 2
} (1, 2) )
When the above function runs, the function can tell it was called with only two arguments via the arguments object's length property. 当上面的函数运行时,该函数可以通过arguments对象的length属性告诉它只有两个参数被调用。
Is there also a way for the function to tell that it was expecting 3 arguments since a, b, & c are listed in the definition of the function? 由于在函数的定义中列出了a,b和c,因此该函数还可以告诉它期望3个参数吗?
In the above function: 在以上功能中:
console.log( what?) === 3?
I read through this answer Get a function's arity but it requires a reference (such as a name) to the function and does not answer my question with respect to the console.log being inside the function. 我仔细阅读了这个答案, 得到了函数的名称,但是它需要对该函数的引用(例如名称),并且对于函数内部的console.log,我没有回答。
You can name your function expression [1] and use that reference to get the arity of the function via its .length
property : 您可以命名函数表达式 [1]并使用该引用通过其
.length
属性获取函数的.length
:
(function iefe(a, b, c) {
console.log(arguments.length); // 2
console.log(iefe.length); // 3
}(1, 2));
1: If you don't care about oldIE bugs. 1:如果您不关心oldIE错误。 If you do and work in sloppy mode,
arguments.callee
might be a better option. 如果您在马虎模式下工作,那么
arguments.callee
可能是一个更好的选择。 Of course you can also use an identifier-leaking function declaration or variable assignment, or - as you always refer to the same function anyway - use a constant value. 当然,您也可以使用标识符泄漏函数声明或变量赋值,或者-就像您始终引用相同的函数一样-使用常量值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.