Inspect the names/values of arguments in the definition/execution of a JavaScript function

clemesha picture clemesha · May 27, 2009 · Viewed 7.4k times · Source

I'm looking to do the equivalent of Python's inspect.getargspec() in Javascript.

I do know that you can get the arguments list from a Javascript function, but what I'm really looking for is the names of the arguments from the originally defined function.

If this is in fact impossible, I'm going to have to 'brute-force' it by getting the string of the function, i.e. myFunc.toString() and then parsing out the ... inside of function myFunc(...). Does anyone know how to do this parsing in a general way?

Thanks for any tips.

Answer

Jonathan Fingland picture Jonathan Fingland · May 27, 2009

While I can't see any good reason for this,

var reg = /\(([\s\S]*?)\)/;
var params = reg.exec(func);
if (params) 
     var param_names = params[1].split(',');

assuming func is the name of your function