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.
window.variable = variable;
Don't understand what is an "automatic mode", so this might not what you wanted.
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
globals
variable instead of using thesetGlobVar
andgetGlobVar
methods 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
window
object) 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
globals
into a namespace that is specific to my application.NOTE: This is actually the same as original module-pattern approach I suggested, just without the
get
andset
accessor methods and coded differently.Call the function as
globVar('myVar','myVarValue')
Here is a jsfiddle: http://jsfiddle.net/emQQm/