0

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?

Community
  • 1
  • 1
Jason Wells
  • 887
  • 6
  • 16
  • 33

2 Answers2

3

To avoid global namespace pollution you should wrap your code in an Immediately Invoked Function Expression (IIFE). JavaScript variables have functional scope so they only exist within the function they're declared in.

(function () {
    //these variables only exist within the outer function
    var foo,
        bar;
    foo = 1;
    bar = 2;

    //these functions only exist within the outer function
    function fizz() {
        return foo + bar;
    }
    function buzz() {
        return foo - bar;
    }
}());

The above example is pretty useless, as all the variables and functions are encapsulated and won't be usable externally. Any functions/variables that need to be global should be manually added to the global object:

(function (g) {
    //not repeating code from above, pretend it's here

    //make the functions globally accessible
    g.fizz = fizz;
    g.buzz = buzz;
}(this));
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • Thanks for the explanation. Yes, I actually wanted to expose the foo and bar variables to other functions on the page. Isn't creating an object for our globals sufficient for avoiding collision? – Jason Wells Jan 12 '13 at 19:20
  • Only if the wrapping object doesn't have a naming collision. – zzzzBov Jan 12 '13 at 19:27
0

Wrap it in a class maybe?

var myPage = {}
myPage.foo = 1;
myPage.bar = 2;
myPage.doStuff = function(newFooValue) {
    this.foo = newFooValue;
}

You would just use one spot in the global scope then. You should avoid this but if you need to address the global scope then you will do it. If you are asking about design patterns you would have to be more precise. If you have two functions named doStuff and doMoreStuff it is a very hard thing to design.

fsw
  • 3,595
  • 3
  • 20
  • 34