[英]How do I combine with and eval but not using with?
var stats = { a:1, b:2, c:3 };
with( stats )
{
console.log( eval( "(a+b)*2" ) );
};
Greetings, I want to be able to perform an eval only within the scope of an object like above, but without using with. 问候,我希望能够仅在上述对象的范围内执行评估,而不能与with一起使用。 I have seen everywhere that its a major no-no to use with :| 我到处都看到它与:|一起使用是一个主要的禁忌。
Its just an example and we don't know what expression is in eval nor the object. 它只是一个示例,我们不知道eval和对象中的表达式是什么。
One possible way: 一种可能的方式:
keys = Object.keys;
values = function(obj) { return keys(obj).map(function(k) {
return obj[k]
})};
var stats = { a:1, b:2, c:3 };
expr = 'a+b*c'
fun = Function.apply(null, keys(stats).concat('return (' + expr + ')'))
result = fun.apply(null, values(stats))
console.log(result) // 7
The same as a reusable function: 与可重用功能相同:
evalWith = function(context, expr) {
return Function.apply(
null, Object.keys(context).concat('return (' + expr + ')')
).apply(null, Object.keys(context).map(function(k) {
return context[k]
}));
}
var stats = { a:1, b:2, c:3 };
result = evalWith(stats, 'a+b*c');
Using eval
: 使用eval
:
evalWith = function(context, expr) {
return eval(Object.keys(context).map(function(k) {
return "var " + k + "= context." + k;
}).concat(expr).join(";"));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.