Namespaces are a common technique used in many programming languages to avoid naming collisions between different parts of your code. Unfortunately JavaScript doesn’t have built in namespace support, but it can be implemented fairly simply by creating a nested hierarchy of objects in the global namespace. A bit like this:

My approach is a little bit different. Your namespace function takes a second argument, a function which is called to initialise your namespace. You can do this by assigning properties to the this object in the function body:

The advantage of this approach is that it implements the JavaScript module pattern, enclosing the entire contents of your file in a single function. Another thing I’ve implemented is the ability to create shortcuts to other namespaces. You can do this by passing them in an additional array to the namespace() function, which then forwards them on to the initialiser: