Global variables in Javascript
Global variables are evil. Although possibly nifty for very small programs it quickly clutters the global namespace and increase the risk for name collisions as are program grows larger. The risk for collisions are even greater when using different libraries and widgets.
There are three ways to define a global variable in Javascript.
The first way is to declare the variable outside of any function.
var myGlobalVar = value;
The second way is to assign it as a property to the global object, which in web browsers are the window object.
window.myGlobalVar = value;
The third way is to use it without defining it. In this case it doesn’t matter if it’s inside of a function or not. This is called implied global.
myGlobalVar = 'Hello world';
A great way to minimize the use of global variables is to store them all in one global object. By doing this you can keep all you variables and functions in one place, greatly reducing the risk for name collisions.
// Define your global object
var myObj = {};
// Add property (variable) to it
myObj.myVar = 'Hello world';
// Add method to it
myObj.myFunctions = function() {
// Do cool stuff
};
The Javascript language was designed with global variables like this to make it easy for beginners to start coding. The side effect being that it’s easy to forget to define a variable and thereby creating bug that are hard to discover. So do yourself a favor and avoid global variables whenever possible.
About the author
Gabriel Svennerberg is an independent Interaction/UI Designer and Web Developer living in Sweden. When he's not busy building web application designed for humans, he writes about all things web on his site In usability we trust. Gabriel is the author of the book Beginning Google Maps API 3 published by Apress.-
http://www.heavyworks.net Jan Seidl
-
http://www.svennerberg.com Gabriel Svennerberg
-
http://mankzblog.wordpress.com Mats
-
http://www.svennerberg.com Gabriel Svennerberg
-
http://www.pixelovers.com/no-conviene-usar-variables-globales-javascript-544325 Anonymous
-
http://derek1906.site50.net Derek
-
MP
-
Jagan