Use of 'const' in ExtendScript
Let's start with an example.
const a = 1;
a = 2;
$.writeln(a); // Prints 1.
Here we can see that 'const' does indeed work. If you want to run this more than once in the ExtendScript Toolkit, be sure to select Debug > Reset from the menu.
Another example:
$.strict = true;
const a = 1;
a = 2; // ReferenceError: a is read only
If strict mode is disabled, reassigning a constant value fails silently. If strict mode is enabled, reassigning a constant value throws an error.
Here's where it starts to get weird:
(function() {
const a = 1;
a = 2;
$.writeln(a); // Prints 2.
})();
Huh? Suddenly 'const' has no effect! Even strict mode doesn't cause the reassignment to fail.
In the earlier examples, "a" is actually a member of $.global. So I got this bright idea:
var object = {};
object.a = null;
with (object) {
const a = 1;
}
object.a = 2;
$.writeln(object.a); // Prints 1.
"a" is constant again! The "with" block locks the value of "a" so it can't be reassigned.
So here's the general rule: Only object properties can be made constant. Local variables cannot be made constant. This means that closure variables cannot be made constant.
To double-check this, I put the previous code inside a function:
(function() {
var object = {};
object.a = null;
with (object) {
const a = 1;
}
object.a = 2;
$.writeln(object.a); // Prints 1.
})();
No problem!
Note that this behavior is not at all like JavaScript. In fact, it's the exact opposite of JavaScript. But still, it's very useful!
Since "with" is considered harmful, it would be nice if we could create constants without using "with". However, due to the syntax requirements of "const", I don't think there's any getting around it.
