javascript - 如何检查函数是否需要参数?

标签 javascript decorator

如何检查 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/

相关文章:

python - 在另一个装饰器之前使用 PyQt 4's ' pyqtSlot' 装饰器的奇怪行为

python - 如何在默认 Django 身份验证登录 View 中使用自定义装饰器

javascript - 只绘制 SVG 圆环图的底部

javascript - $ ('#div' ).bind ('scroll' 函数({})) 不起作用

javascript - 如何在没有 jquery 的情况下使用 javascript 向没有 id 的元素添加 html

javascript - Node.js 中的异步操作是否仅在执行服务器应用程序时才需要?

javascript - 更改 setInterval 的间隔并且所有动画一起运行

java - 这是装饰器模式还是策略模式,还是两者都不是?

python - 让装饰器调用类中特定于方法的 pre 和 post 方法

python - 为什么 list/dict 属性在装饰器之外保留值,而整数属性却没有?