JavaScript and Namespaces (howto)

Michael Schwarz on Thursday, August 25, 2005

On one of my last blogs [1] 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 [2] or Alex Gorbatchev [3].