【问题标题】:Getting names of function arguments [duplicate]获取函数参数的名称[重复]
【发布时间】:2019-03-13 07:54:12
【问题描述】:

我们有一个函数:

function Foo (a,b,c) {
  return a + b + c;
}

需要从函数外部获取 Foo 参数的名称。结果应该是:

Array['a', 'b', 'c']

Foo.arguments 返回null

我看到的唯一方法是调用Foo.toString(),然后解析结果。

还有其他更正确的获取名称的方法吗?

【问题讨论】:

  • 你能重构函数来接收一个结构为{ 'a': null, 'b': null, 'c': null }的对象吗?代码味道?
  • 不,这是一个依赖函数,我无法重构它。

标签: javascript


【解决方案1】:

不,使用Function#toString 似乎是要走的路:

 const str = Foo.toString();
 const args = str.substr(str.indexOf("("), str.indexOf(")")).split(",").map(it => it.trim());

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    相关资源
    最近更新 更多