有什么方法可以在特定范围(但不是全局)上执行 eval()?
例如,以下代码不起作用(第二条语句中 a 未定义),因为它们位于不同的范围内:
eval(var a = 1);
eval(alert(a));
如果可能的话,我想动态创建一个范围。例如(语法肯定是错误的,但只是为了说明想法)
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
}
关于如何实现这样的目标有什么想法吗?谢谢!
最佳答案
您可以使用"use strict"将经过评估的代码包含在评估本身中。
Second,
eval
of strict mode code does not introduce new variables into the surrounding scope. In normal codeeval("var x;")
introduces a variablex
into the surrounding function or the global scope. This means that, in general, in a function containing a call toeval
every name not referring to an argument or local variable must be mapped to a particular definition at runtime (because thateval
might have introduced a new variable that would hide the outer variable). In strict modeeval
creates variables only for the code being evaluated, so eval can't affect whether a name refers to an outer variable or some local variable
var x = 17; //a local variable
var evalX = eval("'use strict'; var x = 42; x"); //eval an x internally
assert(x === 17); //x is still 17 here
assert(evalX === 42); //evalX takes 42 from eval'ed x
如果函数声明为“use strict”,则其中的所有内容都将以严格模式执行。以下将执行与上面相同的操作:
function foo(){
"use strict";
var x = 17;
var evalX = eval("var x = 42; x");
assert(x === 17);
assert(evalX === 42);
}
关于javascript - 在 JavaScript 中指定 eval() 的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9781285/