My webapp is based on a common script where I define the common functions and a global variable and dynamically loaded scripts that process those. So far, the only way I found to export the global variable is to replace any occurrence by window["myGlobalVar"]
but I find it very ugly. Is there a better way to do?
Here is an illustration
// commonscript.js before compilation
function incrementVariable() {window["myGlobalVar"]++;}
window["incrementVariable"] = incrementVariable;
window["myGlobalVar"] = 0;
and in another script
alert(myGlobalVar); // <= alerts 0
incrementVariable();
alert(myGlobalVar); // <= alerts 1
I am looking for a way to use directly myGlobalVar
in both files because it would be more elegant. However, I would need to set window["myGlobalVar"]
to a pointer and not a copy of the object and I am not sure how to do that on simple types.
Is it possible? Is encapsulating myGlobalVar
in an Object
the only other way?
Thanks a lot for your lights.
New Answer
Closure-compiler supports an @nocollapse
annotation which prevents a property from being collapsed to a global variable. This allows the property to be mutable when exported.
@nocollapse
does not block renaming - you still need to export a property to accomplish that.
@nocollapse
is currently only supported when compiling from source. It will be included in the next release - that is versions AFTER the v20150315 release.
Old Answer
@expose
is now deprecated. The compiler will warn about any usage of @expose
There is a new, but so far undocumented, annoatation: @expose. This single annotation will both export a property and prevent it from being collapsed off a constructor. It sounds like the perfect fit for your situation - but it will require your variable to be a property on an object.
However, use with care. Any properties which have @expose will not be renamed and will not be removed as dead code. This makes it especially problematic for use by javascript library writers.
If you want to have a variable that doesn't get renamed, just create a file called for example props.txt
with the following contents:
myGlobalVar:myGlobalVar
Then when compiling your code, add the command line argument: --property_map_input_file props.txt
Your variable will not be renamed and is available to all scripts as long as it's not optimized away. Also, if you don't declare it at all (so you omit var myGlobalVar
), it won't get renamed or removed.