Why does copying eval change its behaviour?

喜你入骨 提交于 2020-06-16 03:35:14

问题


According to the rollupjs documentation:

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
})();

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

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
})();

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
})();

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


回答1:


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.

A more English-friendly description can be found on MDN:

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.



来源:https://stackoverflow.com/questions/62158879/why-does-copying-eval-change-its-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!