如何获取存储在变量中的函数的参数名称?

mai*_*ove 3 javascript reflection

看到这段代码:

var method  = function(service,worker){
   //....
}

function getArguments(method){

  //what I want is: 
  //print " the arguments of the method is 'service','worker'"
}

getArguments(method);
Run Code Online (Sandbox Code Playgroud)

如何从变量中获取参数的名称?

我知道method.arguments在不调用该方法时不起作用.

p.s*_*w.g 8

您可以调用toString该函数,然后使用正则表达式从函数定义中提取参数列表.这是一个简单的例子:

function getArguments(method){
    // strip off comments
    var methodStr = method.toString().replace(/\/\*.*?\*\/|\/\/.*?\n/g, '');
    var argStr = methodStr.match(/\(([^)]*)\)/);
    alert(argStr[1].split(/\s*,\s*/g));
}
Run Code Online (Sandbox Code Playgroud)

示范

  • 不适用于args之间的空间http://jsfiddle.net/BY5N9/2/可以普及吗? (3认同)