javascript - 在 JavaScript 中指定 eval() 的范围?

标签 javascript scope eval

有什么方法可以在特定范围(但不是全局)上执行 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 code eval("var x;") introduces a variable x into the surrounding function or the global scope. This means that, in general, in a function containing a call to eval every name not referring to an argument or local variable must be mapped to a particular definition at runtime (because that eval might have introduced a new variable that would hide the outer variable). In strict mode eval 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/

相关文章:

javascript - 如何在可滚动的 div 中获取对象的相对位置?

javascript - Kendo MVC Chart - 渲染事件问题

python - python中的变量范围

python - 为什么分配给我的全局变量在 Python 中不起作用?

perl - 如何在不使用 eval 的情况下动态包含 Perl 模块?

php - 为老式文件上传添加不显眼的进度条

javascript - 如果数组值已经存在,则删除 JavaScript

javascript - JS 提升如何与 block 语句一起使用?

javascript - 在 Javascript 中使用模板文字进行动态表达式

python - 使用 eval 进行表达式评估的安全性如何?