Right, but it knew you were going to use eval, and to support that, it had to allocate all local variables in the closure. That's why you saw this behavior. The same would happen if you used a 'with' construct.
Wow, so there is actually special handling in the engine for this? So it does static analysis whenever it can, but not in these two cases?
function f() {var x = 99; return function(a,b) {return a(b)};}
f()(eval, 'console.log(x);')
ReferenceError: x is not defined
function f() {var x = 99; return function(a,b) {return eval(b)};}
f()(eval, 'console.log(x);')
99
undefinedThe original assertion by curveship was that the outer context is not kept alive for the function, and that f() only gets access to the variables it explicitly imports from the outer context. And I thought this might be wrong, so I cooked up the example.
Again, this is not about scope. This is about the fact that the function itself keeps a reference to the entire context it was created in, as opposed to just the things it explicitly imports.
In this, it appears, Javascript works exactly as Ruby, which again makes the entire outer context available through the binding facility.
I'm sorry if that wasn't clear from my description.
I'm not sure that's true. Look at the following code:
It's a dynamically named variable. Clearly, f() has access to the entire context that surrounds it, not just the objects explicitly used in the function code. In this example, the compiler could not possibly have known I was going to access x.This means in Javascript, as well as in Ruby, when you hand a closure to my code, I can access the entire environment of that closure.
Contrast that with Lua, for example, where the compiler does indeed check whether an outer variable is being used and then it imports that variable from the context only.
PHP does it most explicitly, forcing the developer to declare what outer objects they want to have available within the function.