JavaScript: creating namespaces

Stoyan Stefanov, in his Object-Oriented JavaScript, proposes an utility function to create JavaScript namespaces inside your library. Namespaces are a basic coding pattern used to avoid collision between libraries. In its essence, this method works as follows:

APP.namespace('dom.style');

instead of writing:

APP.dom = {};
APP.dom.style = {};

Stoyan explains it as follows:

Here's how you can create such a namespace() method. First you create an array by splitting the input string using the period (.) as a separator. Then, for every element in the new array, you add a property to your global object if such a property doesn't already exist.

var APP = {};

APP.namespace = function(name) {
  var parts = name.split('.');
  var current = APP;
  for(var i in parts) {
    if(!current[parts[i]]) {
      current[parts[i]] = {};
    }
    current = current[parts[i]];
  }
}

Usage:

APP.namespace('event');
APP.namespace('dom.style');

This result is exactly the same of writing:

var APP = {
  event: {},
  dom: {
    style: {}
  }
}

Leave a Reply

Note: Only a member of this blog may post a comment.