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
$.global.a = 1;
var a = 2;
$.writeln("$.global.a: " + $.global.a);
will print $.global.a: 2
. This means that $.global.a
and var 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
$.global.a = 1;
$.writeln("a: " + a);
var a = 2;
Running the code
(function() {
$.evalFile("base.jsx");
$.writeln("a: " + a);
$.writeln("$.global.a: " + $.global.a);
})();
changes the scope of base.jsx to be this function instead of the global object. Suddenly $.global.a
and var a
are referring to two different objects. The result of this will be:
a: undefined
a: 2
$.global.a: 1
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.