views:

113

answers:

5

What is the best way to use global variables in Javascript?

Should I do document.x="this", document.y="that"?

How will I avoid collisions in the long run?

+3  A: 

Anything declared outside a function, is, by default, global. You don't need to attach it to document explicitly to make it so. In the long run you WONT avoid collisions which is why this is a Bad Practice.

You can write Object Oriented JS and keep your variables in one name space, more or less.

Erik
+18  A: 

I personally define a namespace for my application data

var myns = {};

and define everything inside that namespace

myns.foo = 50;

In this sense, the only variable you attach to the global object is the namespace object. Everything else is globally accessible, but within your namespace. This reduces collisions on the global object, and eventually you can define a different namespace if you so wish.

Stefano Borini
Nice solution if you don't want to create objects; its what I first did when I realized my variables were clashing with scripts I was using written by others.
Erik
+8  A: 

IMHO, the best way to avoid collisions is to work on a temporary scope, using a self-executing function expression, keeping all your library code encapsulated, and expose your global objects in a very selective way, using as few as possible:

(function(){
  var myLib = window.myLib = function(){ // expose object
    // Initialize
  };
  // ...
})();
CMS
this is also a very nice solution. +1
Stefano Borini
This is an elegant solution and scores bonus points for "thinking in JavaScript." Note that this code is choosing to expose window.myLib; it's not always necessary to do so, and you probably shouldn't when it isn't.
Drew Wills
A: 

As other answers point out, placing your code inside a function prevents it from being globally accessible. You can also use the return value of the function to expose only the variables you want:

var myAPI = (function() {
    var examplePrivateVariable = 1;
    var examplePublicVariable = 1;

    function doSomethingPublic() { /*...*/ }
    function doSomethingPrivate() { /*...*/ }

    return {
        examplePrivateVariable: examplePrivateVariable,
        doSomethingPublic: doSomethingPublic
    };
})();

myAPI.doSomethingPublic();
Tim Down
A: 

I agree with the comments above. I typically create an object, hide the data, and expose getters (rarely) and behavior as needed.

Upper Stage