How to Get Function Parameter Names/Values Dynamically

Get function arguments names and values dynamically

console.log({text, num});

Check ES6 property shorthand notation
http://es6-features.org/#PropertyShorthand

Get function parameter names for interface purposes

I doubt that there is any decent way to this, in javascript parameter values can be of different type when passed, the types doesn't matter but the order thus.

This might not be the answer that you are looking for but this could help at least.

function test(a,b,c,d) {

}

//this will give us the number of parameters defined in the a function.
confirm(test.length);

To really know the names you can parse the function definition

  var str = window['test'].toString();
//str will be "function test(a,b,c,d){}"

Below is a simple parsing test I made:

function test(a,b,c,d)
{

}

var b = function(x,y, z){};
alert(getFnParamNames(b).join(","));
alert(getFnParamNames(test).join(","));

function getFnParamNames(fn){
var fstr = fn.toString();
return fstr.match(/\(.*?\)/)[0].replace(/[()]/gi,'').replace(/\s/gi,'').split(',');
}

In javascript, how to set function parameter names when creating function via new Function() ?

Just specify the parameter name in addition to the function body when invoking new Function:

const myFnBody = " return myParam; ";  // dynamic fn-text, expecting 'myParam' variable.
const myFunc = new Function('myParam', myFnBody); // create the function with the body-text.
const myParamVal = "Hello world."; // setup argument
console.log(myFunc(myParamVal));

Dynamically accessing function arguments

Most of your issues stem from the structure of your route definition. It would make more sense to create direct references to the things you want to use, not noting function references etc down as strings.

get routes() {
return [{
path: '/',
method: this.get,
endpoint: this.home,
paramMap: req => [req.query.ref, req.query.country],
}];
}

Once you make the appropriate changes elsewhere, you no longer have the original problem you described.



Related Topics



Leave a reply



Submit