eval() 使用范围内对象的变量
如何将字符串作为代码执行(使用 eval()
)并为其提供一些变量?例如,我有一个名为 vars
的对象,并且希望代码可以访问它的每个属性,而无需明确指定对象名称。像这样的事情:
function evalWithVariables(func, vars) {
//some magic here
return eval(func);
}
function test() {
var retval = evalWithVariables("a>5", {"a":7});
console.log(retval);
}
哦,代码是可信的,它来自与脚本相同的服务器,它不是用户生成的,我很确定 eval
是这里正确的工具(并且我知道 eval
通常是邪恶的)。
编辑:对我来说最重要的是传递给 eval()
的代码看起来不错,很短,并且不必包含辅助变量名称等。
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);
}
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).
Edit: 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
发现可以只使用
with
:Discovered that it's possible to just use
with
:您可以将这些值重新构造为 JavaScript 代码,并在其前面添加要执行的代码。然后,将实际表达式的结果分配给局部变量。所以,
实际上是
eval
:然后,在
eval
之后,检查result
的值: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,
actually
eval
s:Then, right after the
eval
, check the value ofresult
:放弃
eval()
的一个选项是生成一个函数,然后像您一样使用with()
来更改块作用域:An option to forgo
eval()
is to generate a function and then usewith()
, as you did, to change the block scope:也许您使用更实用的方法:
或更短:
Maybe you use a more functional approach:
Or shorter: