如何检查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的情况下得到解答。
UPDATE :我知道我可以执行if (descriptor.value() === 'undefined')
之类的操作来确定函数是否返回任何值,但在返回的函数中可能并非总是如此。
答案 0 :(得分:4)
您可以查看该功能的length
属性。
length
是函数对象的属性,表示函数期望的参数数量,即形式参数的数量。此数字不包括rest parameter,仅包含具有默认值的第一个参数之前的参数。相比之下,arguments.length
是函数的局部函数,并提供实际传递给函数的参数数量。
function functionWithArgs(arg1, arg2) {}
function functionWithoutArgs() {}
console.log(functionWithArgs.length); // 2
console.log(functionWithoutArgs.length); // 0