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
@nocollapseannotation which prevents a property from being collapsed to a global variable. This allows the property to be mutable when exported.@nocollapsedoes not block renaming – you still need to export a property to accomplish that.@nocollapseis currently only supported when compiling from source. It will be included in the next release – that is versions AFTER the v20150315 release.Old Answer
@exposeis now deprecated. The compiler will warn about any usage of@exposeThere 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.