Although you can reference a "true" global variable by replacing all use of this global variable with window["varname"] , it is generally not recommended to "pollute" the global namespace. The Closure compiler is designed to prevent you from doing this.
CAVEAT : window["varname"] and var varname do not match, since the "window" may not always be a global object in non-working environments. In essence, the Closure Compiler assumes that the global object and the window are different. For example, window["varname"] will compile with window.varname instead of var varname . They are NOT the same, although they work similarly in the browser.
It is best to create a global namespace object and then export only one object. All your βglobalβ variables should become properties in this global namespace variable. Benefits:
- All these global variables are renamed to shorter versions.
- Constants may be nested
- The Closure compiler automatically "aligns" the namespace anyway, so your code will not be slower.
- Excellent obfuscation
- Your code also works in non-browser environments. Remember that a window may not always exist (for example, on the server side), and a global object may not always be a window
If you have global variables that the user must read / set to use your library, this is also discouraging. It is better to set the API for the global namespace object, and then publish the API as usual through the window object: window["myLib"]["setConfig"] = myLib.setConfig .
In your case, if you have global variables used in other parts of your code that are not related to Closure-Compiled, you should consider:
- Is it better to place the declaration of these variables outside the file compiled by Closure
- Why don't you put the declaration of these variables along with code that uses them.
- If you really are a Closure compilation of all code instead of a part (maybe? Are you using a different library?)
source share