Possible Duplicate: How to avoid global variables in JavaScript?
I'm looking for some advice on how best to manage global variables in JavaScript.
Consider the following:
foo = 1;
bar = 2;
// Update our global variable
function doStuff (newFooValue) {
foo = newFooValue
}
// Update a global based on a condition
function doMoreStuff () {
if (bar == 3) {
foo = 1;
}
}
In both cases, our functions are accessing global variables internally, which feels ugly to me. From what I've read, we want to avoid globals as much as possible to avoid clogging up the global name space.
So is creating a structure for our globals all that we need?
For example,
var myPage = {}
myPage.foo = 1;
myPage.bar = 2;
I suppose this solves the global namespace collision problem, but I am still accessing the global scope from within my methods.
What should I do?