Reputation: 273512
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?
Upvotes: 1
Views: 247
Reputation: 3757
I agree with the comments above. I typically create an object, hide the data, and expose getters (rarely) and behavior as needed.
Upvotes: 0
Reputation: 324567
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();
Upvotes: 0
Reputation: 827366
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
};
// ...
})();
Upvotes: 8
Reputation: 143795
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.
Upvotes: 19
Reputation: 20722
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.
Upvotes: 3