For some weeks ago I wrote a post about how to create a class with the ASP.Net AJAX Client Library. In this post I will talk more about how to work with Object-Orientation on the client-side with Java-script, so if you have read my first post about the ASP.Net AJAX Client Library you will get the basics about creating classes so I will not repeat it here, instead I will show you how you can create a base class and sub class and use inheritance.
The following example is a simple base class that represents a Shape:
Type.registerNamespace(’Nsquared2.ASPAJAX.Samples.Shape);
Nsquared2.ASPAJAX.Samples.Shape = function(name, color)
{
this._name = name;
this._color = color;
}
Nsquared2.ASPAJAX.Samples.Shape.prototype =
{
get_Name: function()
{
return this._name;
},
get_Color : function()
{
return this._color;
}
}
Nsquared2.ASPAJAX.Samples.Shape.registerClass(’ Nsquared2.ASPAJAX.Samples.Shape’);
The following code is a class that represents a Square which “is a” shape:
Nsquared2.ASPAJAX.Samples.Square = function(name, color, x, y)
{
Nsquared2.ASPAJAX.Samples.Square.initializeBase(this, [name, color]);
this._x = x;
this._y = y;
}
Nsquared2.ASPAJAX.Samples.Square.prototype =
{
get_x: function()
{
return this._x;
},
get_y: function()
{
return this._y;
}
}
Nsquared2.ASPAJAX.Samples.Square.registerClass(
‘Nsquared2.ASPAJAX.Samples.Square’,Nsquared2.ASPAJAX.Samples.Shape);
var square = new Nsquared2.ASPAJAX.Samples.Square(“My Square”, “red”, 10, 20);
alert(square.get_Color);
When we create a sub class we need to make a call to the initializeBase method from our constructor. If we don’t do that, we can’t access the base class’s members. When the constructor make a call to the initializeBase, it will pass itself (using “this”) and along with the argument that should be passed to the base constructor.
The registerClass method will take the class it should create and also the base class it should extend as an argument. The registerClass can take three possible parameters, the class to create, the base class to extend and the interface that should be used.
This is all we need to create a base and sub class and use inheritance. If we want to make a call to a base class method form the sub class, we can use the callBaseMethod. The following code will override the get_Name property of the base class:
Nsquared2.ASPAJAX.Samples.Square.prototype =
{
…
get_name : function()
{
return “Square’s Name: “ + Nsquared2.ASPAJAX.Samples.Shape.classBaseMethod(this, “get_name”));
}
}
We can also create interfaces and create a class that implements an interface, I will write a separate post about that in a near future ;)