Reputation: 11740
The following needs to be in function scope, since the strange behavior does not occur is interactive console mode.
Following function returns 5 as expected
(function() { var x = 5; return eval("x"); })()
A simple transparent(ish) change:
(function() { var x = 5; var j = eval; return j("x"); })()
yields an error:
ReferenceError: x is not defined
Is this some kind of strange security measure?
Upvotes: 2
Views: 135
Reputation: 166001
Your second example is an indirect call to eval
. Indirect calls to eval
are evaluated in the global scope, where x
is not visible:
var x = 10;
// This will return 10
(function() {
var x = 5;
var j = eval;
return j("x");
})();
// This will return 5
(function() {
var x = 5;
return eval("x");
})();
From the spec:
1. ...if the eval code is not being evaluated by a direct call to the eval function then
a. Initialize the execution context as if it was a global execution context...
Upvotes: 6