Creating namespaces with functions in JavaScript
JavaScript does not have either proper packages nor namespaces support. This can lead to the usual naming conflicts when one mixes JavaScript "libraries" from multiple sources.
I recently had a look at the source code of jQuery and was intrigued by the very first lines of code where an anonymous function is being called and wraps the remainder of the code...
This is how I figured out how people could make namespaces in JavaScript as well as properly hide some attributes and functions from the outside work (recall that JavaScript does not have a notion of private/protected/public visibility).
If you are a seasoned JavaScript developer then please forgive me for not having figured out earlier
The idea is pretty simple: your namespace is a JavaScript object that is created by a function that you call straight along with its definition. In turn, this function returns an object that only contains the "public" attributes and methods that you want to expose. The rest is automatically "private" inside the function.
Testing this is rather easy:
Once again this is neither new nor much difficult to understand, but at least I hope that you will have learned a trick
Related posts:
- Make glossy reflections in JavaScript
- Playing with Berkeley DB Java Edition and Guice
- Guice it up (or AOP can be made simple sometimes)
- Initialization blocks in Java
- Revisiting Guice and AOP with AspectJ

March 1st, 2009 - 12:57
Great article, thank you. Can you explain how to implement child/nested namespaces, example var com.mycomp.section = function() {