Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters to an eval based function inJavascript

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?

like image 409
Saket Nalegaonkar Avatar asked Mar 06 '18 07:03

Saket Nalegaonkar


People also ask

Why we should not use eval in JavaScript?

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.

What is the alternative of eval in JavaScript?

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.

What is $$ eval?

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.


Video Answer


3 Answers

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
like image 97
gurvinder372 Avatar answered Oct 07 '22 07:10

gurvinder372


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));
like image 44
Gerry Avatar answered Oct 07 '22 09:10

Gerry


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);
like image 27
Vasily Ivanov Avatar answered Oct 07 '22 09:10

Vasily Ivanov