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, par
You can also use "esprima" parser to avoid many issues with comments, whitespace and other things inside parameters list.
function getParameters(yourFunction) {
var i,
// safetyValve is necessary, because sole "function () {...}"
// is not a valid syntax
parsed = esprima.parse("safetyValve = " + yourFunction.toString()),
params = parsed.body[0].expression.right.params,
ret = [];
for (i = 0; i < params.length; i += 1) {
// Handle default params. Exe: function defaults(a = 0,b = 2,c = 3){}
if (params[i].type == 'AssignmentPattern') {
ret.push(params[i].left.name)
} else {
ret.push(params[i].name);
}
}
return ret;
}
It works even with code like this:
getParameters(function (hello /*, foo ),* /bar* { */,world) {}); // ["hello", "world"]