Why can’t you access scoped variables using eval under a with statement?
For example:
(function (obj) {
with (obj) {
console.log(a); // prints out obj.a
eval("console.log(a)"); // ReferenceError: a is not defined
}
})({ a: "hello" })
EDIT: As the knowledgeable CMS pointed out, this appears to be a browser bug (browsers that use the WebKit console).
If anyone was wondering what abomination I was trying to come up with that would require both the “evil” eval and with — I was trying to see if I could get a function (used as a callback) executed in another context rather than the one it was defined in. And no, I probably (cough) won’t use this anywhere.. more curious than anything.
(function (context,fn) {
with (context)
eval("("+fn+")()");
})({ a: "hello there" }, function () { console.log(a); })
This is a bug reproducible only from the WebKit’s Console, it has problems binding the caller context when
evalis invoked from aFunctionExpression.When a direct call of
evalis made, the evaluated code as you expect should share both the variable environment:And also the lexical environment:
In the above function
localVarshould be declared on the lexical environment of the caller, not on the global context.For
FunctionDeclarations the behavior is completely normal, if we try:And
I have been able to reproduce the problem on the following browsers running on Windows Vista SP2: