eval(),包含范围内对象的变量 [英] eval() with variables from an object in the scope

查看:124
本文介绍了eval(),包含范围内对象的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何执行字符串作为代码(使用 eval())并给它一些变量?例如,我有一个名为 vars 的对象,并希望代码可以访问它的每个属性,而无需指定对象名称。这样的事情:

how can I execute a string as code (using eval()) and give it some variables? For example, I've got an object named vars and want each of its properties to be accessible for the code without exciplitely specifying the objects name. Something like this:

function evalWithVariables(func, vars) {
 //some magic here
 return eval(func);
}

function test() {
 var retval = evalWithVariables("a>5", {"a":7});
 console.log(retval);
}

哦,代码是可靠的,它来自与脚本,它不是用户生成的,我很确定 eval 是正确的工具(我知道 eval 通常是邪恶的。)

Oh, and the code is trusted, it comes from the same server as the script, it is not user-generated and I'm pretty sure that eval is the right tool here (and I know that eval is often evil).

编辑:对我来说最重要的是传递给<$ c $的代码c> eval()看起来不错,很简短,不必包含辅助变量名等。

The most important thing for me is that the code that gets passed to eval() looks good, is short and doesn't have to contain helper variable names or so.

推荐答案

发现可以只使用

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

这篇关于eval(),包含范围内对象的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆