Creating Namespaces in JavaScript is actually rather simple...

10. July 2007

Creating Namespaces in JavaScript is rather simple due to the fact that JavaScript is a very flexible language. As far as I know all the popular Ajax frameworks do this (including the ASP.NET AJAX Extensions). Being a .NET programmer (I'm assuming Java programmers would feel the same way), having classes devided up into namespaces makes code alot easier to manage.

Here's some code that wraps up the ability to add namespaces into a namespace of it's own:

/// Create the Namespace Manager that we'll use to
/// make creating namespaces a little easier.

if (typeof Namespace == 'undefined') var Namespace = {};
if (!Namespace.Manager) Namespace.Manager = {};

Namespace.Manager = {
 Register:function(namespace){
  namespace = namespace.split('.');

  if(!window[namespace[0]]) window[namespace[0]] = {};
  
  var strFullNamespace = namespace[0];
  for(var i = 1; i < namespace.length; i++)
  {
   strFullNamespace += "." + namespace[i];
   eval("if(!window." + strFullNamespace + ")window." + strFullNamespace + "={};");
  }
 }
};

Here's a sample usage of the above code to create and use an object that's placed inside a namespace:

// Register our Namespace
Namespace.Manager.Register("PietschSoft.Utility.Class");

// Add the Triplet class to the namespace created above
PietschSoft.Utility.Class.Triplet = function(one, two, three)
{
 this.First = one;
 this.Second = two;
 this.Third = three;
}

// Create an instance of our Triplet class
var myTriplet = new PietschSoft.Utility.Class.Triplet("1", "2", "3");

// Read the values out of the properties of you Triplet class
alert(myTriplet.First + "\n" + myTriplet.Second + "\n" + myTriplet.Third);

 

Why would I want this snippet?

Well, you really don't if you use any of the popular Ajax frameworks that implement their own namespace management. But at least this gives you an idea of how it's done. Plus, using this snippet will allow you to utilize namespaces if you are hand coding everything in your app and not using an Ajax framework.

JavaScript

Comments

10/7/2009 2:18:53 PM #
Pingback from purab.wordpress.com

creating the complex multiple namespace JS library with classes «  My Code book
2/14/2010 9:33:28 AM #
Pingback from wordpressapi.com

Creating the multiple namespace JS library with classes | wordpressapi.com
5/20/2010 6:52:06 PM #
Pingback from 125.computeronlinebingo.com

Mustang Mercury Cougar Parts Locating, Cougar Promo Airport
8/7/2011 9:20:34 PM #
Pingback from Joel.InPointForm.net

Joel in point form Essential Tools for *Advanced Javascript Programs » Joel