AJAX and Type.registerNamespace: How it works
If you've developed in JavaScript without the ASP.NET AJAX client-side additions, you know that you typically can't create an object like the following:
function MyNS.MyClass() { }
This is not a supported feature because of the dot notation. This can work in JavaScript by setting up the namespace like the following:
var MyNS = MyNS || { };
And then adding the class to the instance. Using a variable is one way to create the namespace; using the window object is another. By using the following setup of a class:
if (!window["MyNS"])
window["MyNS"] = {};
window["MyNS"].MyClass = function() { }
This approach creates a new object MyClass within the MyNS namespace. MyNS is actually an object that has a MyClass property, which MyClass happens to be a function. This is perfectly valid. So an object can be created via:
var obj = new MyNS.MyClass();
The ASP.NET AJAX way of doing things is using the following approach:
Type.registerNamespace("MyNS");
MyNS.MyClass = function() { .. }
MyNS.MyClass.prototype = { .. }
MyNS.MyClass.registerClass("MyNS.MyClass");
Behind the scenes, ASP.NET AJAX works a very similar way. The Type.registerNamespace static method actually works by creating any global namespaces, and storing a reference with the window. What is a global namespace? For instance, if you had a class named Department.Hardware.Tools.Screwdriver, it would break down as follows:
Department <- global namespace
Hardware <- local namespace
Tools <- local namespace
Screwdriver <- class
And thus, the registerNamespace method passes Department to the window object, creating a new class with the empty class "{}" notation. The Hardware namespace is a class that gets appended to Department, and so on. Notice that you assign the prototype the same way you would in both implementations. The prototype in ASP.NET AJAX and in JavaScript would be:
MyNS.MyClass.prototype = {
get_name: function () { return "my name"; }
}
This is because this is standard javascript; Microsoft does not attempt to replace any existing JavaScript conventions, but to supplement them.