I hear limit your global variables i javascript.
If I have to declare variables in global scope then I will do something like this:
var global1 = 0, global2 = 1, global3 = 2, global4 = 3;
Here I have four global variables. Now I thought of limiting the numbers of global variables and did some thing like this
var globals = {
global1 : 0,
global2 : 1,
global3 : 2,
global4 : 3
}
I wanted to know whether the second method is better or just the same, since by exposing the variable globals I am exposing the other others also.
Your approach is basically called namespacing and is done by most big libraries like, e.g., jQuery uses
jQueryand/or$to hold all of its variables and functions.The main reason for reducing the amount of global vars is to limit possible collisions, if different scripts use the same variable names.
So, e.g., script A defines a global variable
cachefor its internal purposes. When now a second, unrelated script B needs another global variable of that name, you will run into trouble as probably script B will just overwrite the variable of script A.By putting your variables (and functions as well) into a global namespace of your own with a name that probably is not used by any other script, you reduce the probability of the aforementioned to happen.