If you develop a page containing multiple javascript files theres a good chance that sooner or later you are going to declare a function or variable with the same name in multiple files – breaking your code and causing a bug that could be hard to trace. The solution is to place your code inside another uniquely named object, or even chain of objects – called a namespace. A simple solution could look like this:
acme.sales.js
if (acme == null) acme = {};
if (acme.sales == null) acme.sales = {};
acme.sales.addTarget = function() {
...
}
acme.marketing.js
if (acme == null) acme = {};
if (acme.marketing == null) acme.marketing = {};
acme.marketing.addTarget = function() {
...
}
This ensures that the second addTarget function doesn’t overwrite the first.
However, we can improve this code pattern by creating a function. This allows us to take advantage of the this keyword inside the function:
acme.marketing 2.0.js
if (acme == null) acme = {};
if (acme.marketing == null) acme.marketing = new function() {
this.addTarget = function() {
..
}
};
This also provides a useful way of creating public and private methods:
if (acme == null) acme = {};
if (acme.marketing == null) acme.marketing = new function() {
this.addTarget = function() {
..
}
//Private functions
var internal = function() {
..
}
};
The public function addTarget is visible to the namespace, but the internal function isnt.
The namespace function
The namespace function takes these ideas and makes the code more succinct and readable. Using the namespace function, we could rewrite our examples so:
namespace('acme.sales', function() {
this.addTarget = function() {
..
}
}
namespace('acme.marketing', function() {
this.addTarget = function() {
..
}
var internal = function() {
..
}
}
All parent namespaces are created if they dont exist and the namespace is only declared in one place, making it much easier to change if required. If the namespace already exists, you can use the object directly instead of the string representation.