JavaScript namespace support
July 3, 2007
Following up to my previous post about window.onload problems with JavaScript, the other problem I encounter with JavaScript is its lack of namespace support. JavaScript has no concept of namespaces, so there are bound to be conflicts between libraries unless you get lucky and all your JavaScript library authors picked different function and global variable names.
To solve this problem, you can do something rather funky and wrap everything in a function with the same name as the JavaScript library file. Thus, magical JavaScript namespaces, sort of. Here’s the new and “improved” script.js file:
var TestScript = function () {
return {
displayListings : function () {
TestScript._buildStuff(
"place_to_put_stuff",
"Some stuff and things"
);
},
_buildStuff : function ( id, text ) {
var li = document.createElement("li");
li.appendChild( document.createTextNode(text) );
document.getElementById(id).appendChild(li);
}
};
}();
The rest of the script.js file is the same, with the exception of changing every instance of displayListings to TestScript.displayListings. Notice that even within the TestScript “namespace” you have to refer to _buildStuff by it’s full name.
This seems like a neat idea, although I haven’t tried it for anything real. I am curious how it would work when building a larger-scale set of home-grown JavaScript libraries. For the enterprise development environment, you have to either enforce using this solution or enforce some sort of long naming convention.
function TestScript_displayListings() {
TestScript__buildStuff(
"place_to_put_stuff",
"Some stuff and things"
);
}
Both options require enforcing a style and best practice across your enterprise, which means that you have to actually enforce something, which means that it probably won’t get enforced (unless you have free time to enforce things, which means you’re not very busy, which means you should probably get downsized). Which one do you think is easier to enforce?
