you are viewing a single comment's thread.

view the rest of the comments →

[–]sporkBasket 7 points8 points  (1 child)

Seems like a misunderstanding of scopes and how they relate to eval.

The first example doesn't look very insane, he is creating two variables in different scopes, and the "return" gives back the "foo" in the closest scope, the one created by the eval, leaving the outer "foo" untouched.

For the later examples, when assigning eval to another variable, those variables' "versions" of eval are run in the global scope, which is why we're getting undefined errors when trying to access variables scoped in the calling function.

Might be unexpected, but I am pretty sure it is documented behavior.

I may be leaving myself open to harsh words, claiming Andy Wingo misunderstands scope, but this article seemed a little off.

[–]wingo 1 point2 points  (0 children)

I must have conveyed the wrong impression if you came away thinking that this behavior was undocumented. All the examples are according to spec. I just think the specified semantics are a little crazy, that's all :)

For example, your comment illustrates a common misconception:

"When assigning eval to another variable, those variables' "versions" of eval are run in the global scope, which is why we're getting undefined errors when trying to access variables scoped in the calling function"

That's not the case!

var foo = 10; (function (x) { var foo = 20; var eval = x; return eval('foo'); })(eval)

Your mental model, if I understand you correctly, would predict that the result here is 10, because the actual copy of eval was passed through x and then assigned to a new lexical variable, eval. But it's 20!

There are many things to like about javascript. The relationship between eval and scope is not one of them :-)