在 JavaScript 中指定 eval() 的范围? [英] Specify scope for eval() in JavaScript?
问题描述
有什么方法可以在特定范围(但不是全局)上执行 eval()?
is there any way I can execute eval() on a specific scope (but NOT global)?
例如,以下代码不起作用(第二个语句中的 a 未定义),因为它们在不同的范围内:
for example, the following code doesn't work (a is undefined on the second statement) because they are on different scope:
eval(var a = 1);
eval(alert(a));
如果可能,我想即时创建一个范围.例如(语法肯定是错误的,但只是为了说明这个想法)
If possible, I would like to create a scope on the fly. for example (the syntax is definitely wrong, but just to illustrate the idea)
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
}
知道如何实现这样的目标吗?谢谢!
Any idea on how to achieve something like this? Thanks!
推荐答案
你可以使用"use strict" 在 eval 本身中包含 eval 的代码.
you can use the "use strict" to contain the eval'ed code within the eval itself.
其次,严格模式代码的eval
不会在周围的作用域中引入新的变量.在普通代码中,eval("var x;")
将一个变量 x
引入到周围的函数或全局作用域中.这意味着,通常,在包含对 eval
调用的函数中,每个不引用参数或局部变量的名称都必须在运行时映射到特定定义(因为 eval
code> 可能引入了一个新变量来隐藏外部变量).在严格模式下 eval
只为被评估的代码创建变量,所以 eval 不能影响一个名字是指外部变量还是某个局部变量
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",那么里面的所有东西都会以严格模式执行.以下将执行与上述相同的操作:
If a function is declared with "use strict", everything in it will be executed in strict mode. the following will do the same as above:
function foo(){
"use strict";
var x = 17;
var evalX = eval("var x = 42; x");
assert(x === 17);
assert(evalX === 42);
}
这篇关于在 JavaScript 中指定 eval() 的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!