16 December 2013

Namespacing JavaScript can be a relatively tedious endeavor. Since each level of the namespace is actual an object, the code has to establish an object at each level. Creating a new unnecessary module does not take much effort in a node context, but it does take unnecessary requests for client JavaScript. The objective is to create a simple and a (more difficult) short JavaScript snippet to create a namespace via object creation.

The Problem

There is an apparently simple way to create the namespace-simulating object:

var com = { example : { "a" : {} } };

Unfortunately, if you create com.example.a and com.example.b, then the second declaration would override the first.

The Reference Solution

This is a verbose but complete JS solution to create the namespace object hierarchy.

if (typeof com == 'undefined') var com = {};
if (typeof com.example == 'undefined') com.example = {};
com.example.a = {};

A Nice External Solution

An external module is nice, but it is debatable whether it is simple or short. Nevertheless, here is a good example for an external solution that simply requires a call to MyNS.CreateNamespace() from https://gist.github.com/JamesMGreene/3070677. That is a great example, but Array.prototype.reduce() is not available in IE until IE9.

A Short Multi-Namespace Solution

This concise solution creates multiple namespaces. This gets us IE5.5

(function(x){var n,p=window,s;while(x.length){s=x.shift().split('.');while(s.length){n=s.shift();p=(p[n]=p[n]||{})}}})([

The function above gets us IE5.5 (limited by shift).

A Short Single-Namespace Solution

The same solution without the mult-namespace support would be:

(function(x){var n,p=window,s;s=x.split('.');while(s.length){n=s.shift();p=(p[n]=p[n]||{})}})("com.example.a");

One More Play on the Reference

This retains both the high readability and high compatibility of some other solutions.

window.com.example.a = {};

blog comments powered by Disqus