JavaScript and Namespaces (howto)

On one of my last blogs I wrote about the way using namespaces in JavaScript. Some developers asked me how to create namespaces in JavaScript. Following short example will have a registerNS method which will create the necessary objects (our namespaces).

<script language="javascript">

function registerNS(ns)
{
 var nsParts = ns.split(".");
 var root = window;

 for(var i=0; i<nsParts.length; i++)
 {
  if(typeof root[nsParts[i]] == "undefined")
   root[nsParts[i]] = new Object();

  root = root[nsParts[i]];
 }
}


registerNS("Michael.Ajax.Utilities");

Michael.Ajax.Utilities.RegisterCallback = function(e, callback)
{

 // ...
}

Michael.Ajax.WebService = function(wsdl, async)
{
 this.wsdl = wsdl;
 this.async = async;

 // ...
}

// sample usage

var ws = new Michael.Ajax.WebService(http://.../service1.asmx?WSDL, true);
ws.onready = function(res)
{
 alert(res.value);
}
ws.ServerAdd(21, 2);

</script>

The call registerNS("Michael.Ajax.Utilities"); will create an object Michael with a property Ajax. The Michael.Ajax itself will have a property Utilities which can be accessed using Michael.Ajax.Utilities. So, what you have to use in the registerNS method is the largest namespace you want to add.

There are different ways how to create namespaces in JavaScript: Wikipedia or Alex Gorbatchev.

Published Friday, August 26, 2005 12:24 AM by Michael Schwarz

Comments

No Comments