Over the past 10 or so years I've written a lot of JavaScript. From very early on, at Caplin Systems, I had to write things in a way which ensured that code was clear, usable, discoverable, reusable, extensible and can easily built upon. One of the concepts that was used was to put code within a namespace. This ensured that you couldn't accidentally override a function in the global window namespace and also meant that the namespace would describe the sort of functionality contained within. I've continued to use this concept in various forms but just realised that I've never actually shared how I do this. So here goes.
It's actually really simple. I've got two functions that I use, and I've recently ported over to the com.pusher namespace since I'm creating demos for my work (and play). The first creates some default namespace objects and then defines a namespace function that can be used from then on to create any other namespace objects.
/**
* @namespace
* Top-level namespace to stop namespace clutter.
*/
if(!window["com"]) {
window["com"] = {};
}
Read more...