为什么复制eval会改变其行为? [英] Why does copying eval change its behaviour?

查看:90
本文介绍了为什么复制eval会改变其行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 rollupjs文档


简单地复制 eval为您提供了功能完全相同的功能,但是它在全局范围而不是本地范围内运行:

Simply 'copying' eval provides you with a function that does exactly the same thing, but which runs in the global scope rather than the local one:



var eval2 = eval;
(function () {
   var foo = 42;
   eval('console.log("with eval:",foo)');  // logs 'with eval: 42'
   eval2('console.log("with eval2:",foo)'); // throws ReferenceError
})();

有人能确切解释它的工作原理吗?我无法在ECMAScript规范中找到有关 eval()的任何具体信息。

Can anyone explain exactly how this works? I haven't been able to find anything specific about eval() in the ECMAScript spec.

也许 eval 实际上不是一个函数,而是一个魔术令牌,该令牌被执行该范围内代码的函数所代替,有点像这样:

Perhaps eval is not actually a function, but a magic token that gets replaced by a function that executes code in that scope, a bit like this:

var eval2 = CREATE_EVAL(CURRENT_SCOPE);
(function () {
   var foo = 42;
   CREATE_EVAL(CURRENT_SCOPE)('console.log("with eval:",foo)');  // logs 'with eval: 42'
   eval2('console.log("with eval2:",foo)'); // throws ReferenceError
})();

但是,由于我们在这里处理模块(commonJS或ES6),因此这意味着 eval2 实际上在模块作用域中运行。 rollupjs文档专门说它在全局范围内运行-我认为这只是一个疏忽,但是当我对其进行测试时,它实际上似乎在全局范围内运行:

However, since we're dealing with modules here (commonJS or ES6), this would imply that eval2 actually runs in the module scope. The rollupjs documentation specifically says it runs in global scope - I figured this was just an oversight, but when I tested this, it does actually appear to run in the global scope:

var x = 1;
var eval2 = eval;
(function () {
    eval2('console.log("with eval2:", x)'); // throws ReferenceError
})();

这太令人困惑了!这在世界上如何运作?为什么将引用复制到eval会如此剧烈地改变其行为?

That's very confusing! How in the world does this work? Why does copying the reference to eval change its behaviour so drastically?

推荐答案

因为 ECMAScript 5语言规范表示直接引用 eval 将在本地范围内执行,而间接引用将使用全局范围。

Because the ECMAScript 5 language specification says that direct references to eval will execute in the local scope, while indirect references will use the global scope.

MDN


如果您通过eval以外的引用间接调用eval函数,则从ECMAScript 5开始,它将在全局范围而不是局部范围内工作。例如,这意味着函数声明创建了全局函数,并且被评估的代码无法访问被调用范围内的局部变量。

If you use the eval function indirectly, by invoking it via a reference other than eval, as of ECMAScript 5 it works in the global scope rather than the 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会改变其行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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