How can I get the parameter names of a function stored in a variable?

See this code:

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

function getArguments(method){

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

getArguments(method);

How can I get the names of the parameters from the variable?

I know method.arguments will not work when the method is not called.

Answers


You can call toString on the function, then use a regular expression to extract the argument list from the function definition. Here's a simple example:

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

Demonstration


Need Your Help

Best practice for placement of large test datasets?

maven svn jenkins dataset integration-testing

I'm dealing with an enormous amount of data (say, video) and most integration tests require at least a decent subset of this data.