How should I create a changing variable as a global variable?
so something like:
function globVar(variable){
window.variable;
}
So in this way I could create global variables in an automatic mode too, and also I could create them for myself easier 🙂
EDIT
For example I could create a global variable just like this: globVar('myVariable'); then myVariable is added to the global variables.
Sorry to say this, but the answers you have received are bad habits that you should stay away from. A better programming practice, and perhaps the proper programming practice, would be to pseudo-namespace your global variables so to not clutter the Global namespace/scope. The reasoning behind this is to make your code more manageable, and more importantly, make life easier for you if/when your application becomes large. A simple mechanism to define a namespace is to use the module-pattern made famous by Douglas Crockford.
Here’s a simple example:
To use this, you simply call it like methods of an object.
You could also expose the
globalsvariable instead of using thesetGlobVarandgetGlobVarmethods to use it, if you wanted to simplify how you access the variable.The point is to stay away from defining variables in the global namespace (i.e., the
windowobject) as much as possible, by creating a namespace of your own. This reduces the chance of name collisions, accidentally rewrites or overrides, and again, global namespace clutter.An even simpler approach to doing this is to simply define an object and augment its properties.
Though I would extend this approach by wrapping
globalsinto a namespace that is specific to my application.NOTE: This is actually the same as original module-pattern approach I suggested, just without the
getandsetaccessor methods and coded differently.