Home
Manage Your Code
Snippet: Namespace registration (JavaScript)
Title: Namespace registration Language: JavaScript
Description: Simulates namespaces in Javascript by taking and dividing up a dot-separated string and creating empty objects for each namespace depth. Views: 251
Author: Ben Ramey Date Added: 11/16/2009
Copy Code  
registerNamespace: function(nspace)
{
  var collection = nspace.split('.');
  var registeredNamespace = collection[0];
  var root = window

  for (var i = 0; i < collection.length; i++)
  {
    if (!root[collection[i]])
    {
      root[collection[i]] = {};
    }
    root = root[collection[i]];
  }
}
Usage
Used for easy creation of a namespace "path" so that you don't have to create each object along the way manually.  You pass in a string like "Bob.Joe.Sam" and get the object structure
Bob = {
  Joe: {
    Sam: {
    }
  }
}