问题
I am storing function body in string with function name.
function fnRandom(lim){
var data=[];
for(var i=0;i<lim;i++)
{
data=data.concat(Math.floor((Math.random() * 100) + 1));
}
return data;
}
After selecting the functionName from a drop down I use eval to execute function body.
JSON.stringify(eval(this.selectedFunction.body));
I want to pass 'lim' to this execution or can I use functionName as initiating point for execution somehow?
回答1:
Use Function constructor
var body = "console.log(arguments)"
var func = new Function( body );
func.call( null, 1, 2 ); //invoke the function using arguments
with named parameters
var body = "function( a, b ){ console.log(a, b) }"
var wrap = s => "{ return " + body + " };" //return the block having function expression
var func = new Function( wrap(body) );
func.call( null ).call( null, 1, 2 ); //invoke the function using arguments
回答2:
Eval evaluates whatever you give it to and returns even a function.
var x = eval('(y)=>y+1');
x(3) // return 4
So you can use it like this:
var lim = 3;
var body = 'return lim+1;';
JSON.stringify(eval('(lim) => {' + body + '}')(lim)); //returns "4"
Another way using Function:
var lim = 3;
JSON.stringify((new Function('lim', this.selectedFunction.body))(lim));
来源:https://stackoverflow.com/questions/49125059/how-to-pass-parameters-to-an-eval-based-function-injavascript