在JavaScript中指定eval()的范围? [英] Specify scope for eval() in JavaScript?

查看:125
本文介绍了在JavaScript中指定eval()的范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以在特定范围内执行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 可能引入了一个隐藏外部变量的新变量。 在严格模式下 eval 仅为正在评估的代码创建变量,因此eval不会影响名称是指外部变量还是某个局部变量

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声明函数,其中的所有内容都将以严格模式执行。以下内容与上述相同:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆