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?
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension.
An alternative to eval is Function() . Just like eval() , Function() takes some expression as a string for execution, except, rather than outputting the result directly, it returns an anonymous function to you that you can call.
page.$$eval(selector, pageFunction[, ...args])This method runs Array. from(document. querySelectorAll(selector)) within the page and passes it as the first argument to pageFunction . If pageFunction returns a Promise, then page. $$eval would wait for the promise to resolve and return its value.
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
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));
You can use the Function object.
var param1 = 666;
var param2 = 'ABC';
var dynamicJS = 'return `Param1 = ${param1}, Param2 = ${param2}`';
var func = new Function('param1', 'param2', dynamicJS);
var result = func(param1, param2);
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With