I’m writing a Javascript library that I hope to be able to minify with the Closure Compiler’s ADVANCED_OPTIMIZATIONS option. The library has maybe two dozen global variables which set lower and upper range limits, string literals, etc.
To make these variable accessible from other source files and to avoid dead code removal, I have to “export” them. See Advanced Compilation and Externs.
Therefore, rather than declare variables with this syntax:
var fooMinValue = 10;
I plan to use this syntax:
window['fooMinValue'] = 10;
I’ve tested this and it seems to work fine. My questions are, is there any downside to using this syntax and is it supported in all browsers released since IE 6? (Or should I be using a completely different technique altogether?)
Although both are properties of the global object, there is a difference: when you declare the variable with
var, its[[Configurable]]internal attribute gets set tofalse. Therefore, it’s not possible to change its attributes withObject.defineProperty(except for[[Value]]). The most notable effect is that such variables cannot bedeleted:Also, when assigning a variable to a property, you make a COPY of the value instead of referencing the variable. This means external changes to the property don’t affect the value of the variable.
The above code will produce the following output: