eval() with variables from an object in the scope

廉价感情. 提交于 2019-12-06 07:33:35

Discovered that it's possible to just use with:

eval("with (vars) {var result = (" + func + ")}");

You can reconstitute the values as JavaScript code and prepend it the code to be executed. Then, assign the result of the actual expression to a local variable. So,

evalWithVariables("a>5", {"a":7});

actually evals:

var a=7; var result = (a>5);

Then, right after the eval, check the value of result:

function evalWithVariables(func, vars) {
 var varString = "";

 for (var i in vars)
     varString += "var " + i + " = " + vars[i] + ";";   

 eval(varString + "; var result = (" + func + ")");
 return result;
}

An option to forgo eval() is to generate a function and then use with(), as you did, to change the block scope:

function evalWithVariables(func, vars) {
    return new Function("v", "with (v) { return (" + func +")}")(vars);
}

Maybe you use a more functional approach:

function evalWithVariables(func, vars) {
    return func(vars);
}
evalWithVariables(function(vars) { return vars.a > 5; }, {"a":7})

Or shorter:

(function(vars) { return vars.a > 5; })({"a":7})
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!