3

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?

dln385
  • 11,630
  • 12
  • 48
  • 58
  • 1
    Javascript has a lot of quirks, which I believe are mostly "historical", not some well designed thought (just what happened to be done by some first implementation). Don't try to find logical reasons for every misfeature of Javascript... – Basile Starynkevitch Apr 09 '13 at 15:47
  • 1
    @Basile My goal is to be able to predict the result of my code before running it. Is there a rule that ExtendScript is following here, or is it just a huge collection of quirks and edge-cases that cannot be adequately defined by a set of rules? – dln385 Apr 09 '13 at 15:52
  • Then, adopt some coding rules, including declaring by `var` your variables at the beginning of the function containing it... – Basile Starynkevitch Apr 09 '13 at 15:58
  • I find the "parsing" adjective quite confusing and wrong. The `var` keyword is surely parsed (because parsing is left to right). What matters is the scoping of the declared variable. – Basile Starynkevitch Apr 09 '13 at 17:38

1 Answers1

2

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.

dln385
  • 11,630
  • 12
  • 48
  • 58