Others have answered about why not, but as far as your question on other options, you can use a limited number of objects, whether one created with the new
keyword, or a simple literal, e.g.,:
var justOneGlobal = {
someVariable1: 15,
anotherVariable2: function () {alert('hello!');}
};
...which lessons the likelihood of interference since the only way this would be likely to conflict would be if someone else named their variable justOneGlobal
.
Some people use the formal namespacing approach, as used in Java, like the following:
var com;
if (!com) {
com = {};
}
if (!com.mySite) {
com.mySite = {};
}
if (!com.mySite.example) {
com.mySite.example = {};
}
com.mySite.example.someVariable1 = 15;
...but this approach feels pretty awkward and alien to JavaScript.
One handy way is to use an anonymous function. This prevents ANY globals at all (unless you wish to export some out of the function):
(function () {
// Put all your code in here, making sure to use "var" when defining variables
var someVariable1 = 15;
}());
// Code outside here won't know about `someVariable1`, so conflict is minimized.
Just because one has no global JavaScript variables does not mean, however, that one is guaranteed to avoid conflicts with other drop-in code.
One example, is if someone overrides the prototype of built-in objects, e.g.,:
Object.prototype.repeat = function (num) {
return new Array(num+1).join(this);
};
...and then you try to use a for-in loop, you will actually bump into their code:
var str = 'abc';
for (var i in str) {
alert(i); // "repeat" now shows up here
}
You can protect yourself against this as follows:
var str = 'abc';
for (var i in str) {
if (str.hasOwnProperty(i)) {
alert(i); // "repeat" now shows up here
}
}
Similarly, if you modify the HTML DOM in a certain way, e.g., to add attributes onto elements as a means of keeping track of an element's state, if another application seeks to read or write attributes with the same name, there could be problems. The data-* attributes are meant to be used for storing data, but they don't provide formal namespacing (unlike namespaced attributes were going to promise for XML/XHTML), so there is some risk of one web application using the same attributes.
And this applies not only to what would be visible in mark-up like elements or attributes, but also "invisible" events, e.g., if you attach events in the old style without using addEventListener
(or even if you do but someone calls preventDefault()
or stopPropagation()
), you (or other person) could overwrite one another's events.