gpt4 book ai didi

javascript - 关于模块的 Eloquent javascript 章节。关于作用域和 eval 函数

转载 作者:行者123 更新时间:2023-12-03 09:52:03 25 4
gpt4 key购买 nike

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一个工作示例

关于javascript - 关于模块的 Eloquent javascript 章节。关于作用域和 eval 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30858362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com