如何检查 JavaScript 中的函数是否需要参数才能执行?
function functionWithArgs(arg1, arg2) {...}
function functionWithoutArgs() { /* I will return a function here */ }
我通过 ES7 装饰器检查函数是否有任何参数,因此在检查它们时我不知道函数名称。
装饰器内部
// If the function has arguments, use descriptor.value without invoking it
if (descriptor.value.HAS_ARGUMENTS) descriptor.value;
// If the function has no arguments, invoke it as it will return a function with arguments
else descriptor.value();
虽然我使用的是ES7装饰器,但这个问题应该可以在没有任何ES7知识的情况下回答。
更新:我知道我可以执行类似 if (descriptor.value() === 'undefined')
的操作来确定函数是否返回任何值,但返回函数中的情况可能并不总是如此。
最佳答案
您可以查看length
函数的属性。
length
is a property of a function object, and indicates how many arguments the function expects, i.e. the number of formal parameters. This number excludes the rest parameter and only includes parameters before the first one with a default value. By contrast,arguments.length
is local to a function and provides the number of arguments actually passed to the function.
function functionWithArgs(arg1, arg2) {}
function functionWithoutArgs() {}
console.log(functionWithArgs.length); // 2
console.log(functionWithoutArgs.length); // 0
关于javascript - 如何检查函数是否需要参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41739738/