NetBen Ramblings about JavaScript and frontend development.

23Feb/09Off

The Namespace Pattern.

I'm constantly writing javascript libraries or writing new modules for other libraries (95% of which never sees daylight...) and I used to tie it all together with namespaces. I also used a lot of private variables within my libraries or modules, so I eventually thought to myself, why not do it all in one simple pattern everyone actually uses all the time already.

(function(ns){
    ns = ns || window;
    var myPrivate = "value";
    var method = function(){ /* do stuff with private */ }
    ns.method = method;
})(NameSpace); //<-- insert namespace here.

It basically keeps all my code portable and I never have any conflict issues. If for example John Resig's Sizzle was written this way, it would be dead simple to copy paste code and incorporate it within other libraries/framework. Ofcourse it takes little work to refactor a script to this purpose, but then you'd have to refactor it every single time someone released a new version and removing any eventuality of namespace assignments as well.

It's deadsimple, low level and not even complex enough to deserve a name, but I'll name it anyways: The Namespace Pattern.

\o/ @ first blogpost.

Filed under: JavaScript No Comments