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?