eloquent javascript 关于模块的章节。关于作用域和 eval 函数
eloquent javascript chapter regarding modules. On scopes and eval function
Eloquent javscript 在模块章节的第 10 章中写道:
The most obvious way is the special operator eval, which will execute
a string of code in the current scope. This is usually a bad idea
because it breaks some of the sane properties that scopes normally
have, such as being isolated from the outside world.
代码如下:
function evalAndReturnX(code) {
eval(code);
return x;
}
console.log(evalAndReturnX("var x = 2"));
console.log(x)
console.log(code)
它输出:
2
ReferenceError: x is not defined (line 7)
哪个看起来很正常?是什么赋予了?我没有发现任何违反范围的情况?
Eval 有一些棘手的语义。来自 mdn:
If you use the eval function indirectly, by invoking it via a
reference other than eval, as of ECMAScript 5 it works at global scope
rather than local scope; this means, for instance, that function
declarations create global functions, and that the code being
evaluated doesn't have access to local variables within the scope
where it's being called.
所以在你的情况下,因为你直接在该函数内调用 eval
,它在该函数的词法范围内定义了 x
,不适用于全局范围。但是,如果您要执行以下操作:
var _eval = eval;
function e() {
_eval("var x = 2");
return x;
}
console.log(e());
console.log(x);
它在这两种情况下都有效,因为这将在全局范围内定义 x
,这将由被调用者的词法范围继承。
有关工作示例,请参阅 this fiddle
Eloquent javscript 在模块章节的第 10 章中写道:
The most obvious way is the special operator eval, which will execute a string of code in the current scope. This is usually a bad idea because it breaks some of the sane properties that scopes normally have, such as being isolated from the outside world.
代码如下:
function evalAndReturnX(code) {
eval(code);
return x;
}
console.log(evalAndReturnX("var x = 2"));
console.log(x)
console.log(code)
它输出:
2
ReferenceError: x is not defined (line 7)
哪个看起来很正常?是什么赋予了?我没有发现任何违反范围的情况?
Eval 有一些棘手的语义。来自 mdn:
If you use the eval function indirectly, by invoking it via a reference other than eval, as of ECMAScript 5 it works at global scope rather than local scope; this means, for instance, that function declarations create global functions, and that the code being evaluated doesn't have access to local variables within the scope where it's being called.
所以在你的情况下,因为你直接在该函数内调用 eval
,它在该函数的词法范围内定义了 x
,不适用于全局范围。但是,如果您要执行以下操作:
var _eval = eval;
function e() {
_eval("var x = 2");
return x;
}
console.log(e());
console.log(x);
它在这两种情况下都有效,因为这将在全局范围内定义 x
,这将由被调用者的词法范围继承。
有关工作示例,请参阅 this fiddle