简体   繁体   English

如何在 Javascript 中将参数传递给基于 function 的 eval

[英]How to pass parameters to an eval based function inJavascript

I am storing function body in string with function name.我将 function 正文存储在名称为 function 的字符串中。

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.从下拉列表中选择 functionName 后,我使用 eval 执行 function 主体。

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?我想将“lim”传递给此执行,或者我可以使用 functionName 作为执行的起始点吗?

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. Eval 评估你给它的任何东西,甚至返回一个函数。

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

I'm using vuejs, so the code will be like this我用的是vuejs,所以代码是这样的

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()开发者 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.间接评估在全局 scope 而不是本地 scope 中工作,被评估的代码无法访问调用它的 scope 中的局部变量。

  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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM