获取javascript函数对象的参数个数(甚至名称) [英] Get argument count (or even names) of javascript function object

查看:287
本文介绍了获取javascript函数对象的参数个数(甚至名称)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在接受它之前评估回调函数。这意味着我需要知道至少接受的argumens的数量 - 如果count不匹配,我会在控制台中留下警告。
但是我找不到,javascript函数对象是否有一个属性可以帮助我获取这些信息。

因此,如果没有解析函数,就可以实现作为字符串(不值得)?

I want to evaluate callback function before accepting it. This means I need to know at least the count of accepted argumens - if count doesn't match, I'll leave warning in console. But I can't find out, whether a javascript function object has a property that would help me get that information.
So can this be achieved without parsing function as string (not worth it)?

推荐答案

一个函数有 a length 属性,它告诉你它接受多少个命名的参数。但是请注意,函数可以使用参数变量访问变量,即使它没有命名它们; 长度不适合这个(也没有替代方法)。

A function has a length property which tells you how many named arguments it accepts. Note however, a function can use the arguments variable to access variables, even if it doesn't name them; length doesn't cater for this (nor is there an alternative which does).

function foo(a, b) {
    for (var i=0;i<arguments.length;i++) {
        console.log(arguments[i]);
    }
}

console.log(foo.length); // reports 2, even though `foo` can access all your arguments!

这篇关于获取javascript函数对象的参数个数(甚至名称)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆