Is there a way to get the function parameter names of a function dynamically?
Let’s say my function looks like this:
function doSomething(param1, param2, .... paramN){
// fill an array with the parameter name and value
// some other code
}
Now, how would I get a list of the parameter names and their values into an array from inside the function?
The proper way to do this is to use a JS parser. Here is an example using acorn.
The code here finds the names of the three (formal) parameters of the function
f
. It does so by feedingf
intoacorn.parse()
.Below is the code taken from AngularJS which uses the technique for its dependency injection mechanism.
And here is an explanation of it taken from http://docs.angularjs.org/tutorial/step_05
Whatever the solution, it must not break on wierd functions, whose
toString()
looks just as wierd:Also, why use complex regular expressions? This can be done like:
This works everywhere with every function, and the only regex is whitespace removal that doesn't even process the whole string due to the
.split
trick.Ok so an old question with plenty of adequate answers. here is my offering that does not use regex, except for the menial task of stripping whitespace . (I should note that the "strips_comments" function actually spaces them out, rather than physically remove them. that's because i use it elsewhere and for various reasons need the locations of the original non comment tokens to stay intact)
It's a fairly lengthy block of code as this pasting includes a mini test framework.
The answer to this requires 3 steps:
argValues
). This is straight forward as it will be available asarguments
inside the function.argNames
). This not as easy and requires parsing the function. Instead of doing the complex regex yourself and worrying about edge cases (default parameters, comments, ...), you can use a library like babylon that will parse the function into an abstract syntax tree from which you can obtain the names of parameters.The code will be like this
and the logged object will be
And here's a working example https://tonicdev.com/5763eb77a945f41300f62a79/5763eb77a945f41300f62a7a
=> [ "a", "b", "c" ]