eval函数是一种动态生成代码的强大而简单的方法,那么有什么警告呢?
有什么办法可以在特定范围内执行eval()(但不是全局)?
例如,以下代码不起作用(在第二个语句中未定义)因为它们位于不同的范围内:
eval(var a = 1);
eval(alert(a));
Run Code Online (Sandbox Code Playgroud)
如果可能的话,我想动态创建一个范围.例如(语法肯定是错误的,但只是为了说明这个想法)
var scope1;
var scope2;
with scope1{
eval(var a = 1); eval(alert(a)); // this will alert 1
}
with scope2{
eval(var a = 1); eval(a++); eval(alert(a)); // this will alert 2
}
with scope1{
eval(a += 2); eval(alert(a)); // this will alert 3 because a is already defined in scope1
}
Run Code Online (Sandbox Code Playgroud)
有关如何实现这样的事情的任何想法?谢谢!
我们希望让用户能够在我们的应用程序中执行自己创建的JavaScript代码.为此,我们需要eval用来评估代码.为了将所有安全问题降至最低(如果不是零),我们的想法是防止在代码中使用任何window或document函数.所以没有XMLHttpRequest或类似的东西.
这是代码:
function secure_eval(s) {
var ret;
(function(){
var copyXMLHttpRequest = XMLHttpRequest; // save orginal function in copy
XMLHttpRequest = undefined; // make orignal function unavailable
(function() {
var copyXMLHttpRequest; // prevent access to copy
try {
ret = eval(s)
} catch(e) {
console.log("syntax error or illegal function used");
}
}())
XMLHttpRequest = copyXMLHttpRequest; // restore original function
}())
return ret;
}
Run Code Online (Sandbox Code Playgroud)
其工作原理如下:
secure_eval('new XMLHttpRequest()'); // ==> "illegal function used"
Run Code Online (Sandbox Code Playgroud)
现在我有几个问题:
我试图在特定的上下文中执行eval.我发现这里的答案很有用.但是,我在Chrome版本53.0.2785.143 m中收到以下行为.没试过其他浏览器.我使用的代码如下:
function evalInContext(js, context) {
return function() { return eval(js); }.call(context);
}
console.log(evalInContext('x==3', { x : 3})) // Throws
console.log(evalInContext('this.x==3', { x : 3})) // OK
Run Code Online (Sandbox Code Playgroud)
不过我期待第一次打电话evalInContext不要扔.任何想法为什么会这样?
此代码运行最佳并且易于理解:
function evalInScope(js, contextAsScope) {
//# Return the results of the in-line anonymous function we .call with the passed context
return function() {
with(this) {
return eval(js);
};
}.call(contextAsScope);
}
evalInScope("a + b", {a: 1, b: 2}); // 3 obviously, but fails in strict mode!
Run Code Online (Sandbox Code Playgroud)
然而,“聪明”的大脑决定删除该with声明,而不进行适当的替换。
问题:如何让它在自动处于严格模式的 ES6 中再次工作?