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.
myGlobalVara private obfuscated variable, and provide aGetMyGlobalVarfunction. This way, at least you reduce the instances ofwindow["myGlobalVar"]everywhere in your code.window["mynamespace"] = { "incrementVariable":incrementVariable, "getMyGlobalVar":function() { return myGlobalVar }};Then you can do:alert(mynamespace.getMyGlobalVar()); mynamespace.incrementVariable(); ...Objectwas not so great either. I would have the same issue with the object members which names would be obfuscated. I'd still need getter and setter.