Sometimes var
affects code before it, and sometimes not. Take this example:
base.jsx:
$.global.a = 1;
$.writeln("a: " + a);
var a = 2;
Running this prints a: 1
. Running $.evalFile("base.jsx");
also prints a: 1
. However, running
(function() {
$.evalFile("base.jsx");
})();
prints a: undefined
.
Why? What is the logic behind this?
After a bunch of testing, I figured it out.
I knew that JavaScript's scopes are function-level, but I had assumed that files also have their own scope. I was wrong.
Running
will print
$.global.a: 2
. This means that$.global.a
andvar a
are exactly the same thing in this context, and the scope of the file is actually the global scope.Given that base.jsx is still
Running the code
changes the scope of base.jsx to be this function instead of the global object. Suddenly
$.global.a
andvar a
are referring to two different objects. The result of this will be:So the problem was never that
var
is sometimes parsed early and sometimes not. The problem is that files have no scope other than the global one.