Saket Nalegaonkar
Saket Nalegaonkar

Reputation: 160

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?

Upvotes: 13

Views: 23518

Answers (5)

user21767503
user21767503

Reputation: 1

var body = "console.log(arguments)"

var func = new Function( body );
func.call( null, 1, 2 ); //invoke the function using arguments

Upvotes: 0

Murtadha AlRubayee
Murtadha AlRubayee

Reputation: 3

I'm using vuejs, so the code will be like this

getTargetfunction(funcN, o_id, i_id) {
            console.log(funcN, o_id, i_id);
            const x = o_id;
            const y = i_id;
            eval("this." + funcN + "(x,y)");
        },

in the developer mozilla eval()

Indirect eval works in the global scope rather than the local scope, and the code being evaluated doesn't have access to local variables within the scope where it's being called.

  function test() {
  const x = 2;
  const y = 4;
  // Direct call, uses local scope
  console.log(eval("x + y")); // Result is 6
  console.log(eval?.("x + y")); // Uses global scope, throws because x is undefined
}

Upvotes: 0

Vasily Ivanov
Vasily Ivanov

Reputation: 380

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);

Upvotes: 4

Gerry
Gerry

Reputation: 409

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));

Upvotes: 13

gurvinder372
gurvinder372

Reputation: 68393

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

Upvotes: 22

Related Questions