- Hybrid constructor/prototype paradigm
- Dynanuc prototying
- Using xbObjects (need an external xbObjects.js library file)
Sample Code :
test1.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script type="text/javascript" src="xbObjects.js"></script>
<script language="javascript">
// Example of hybrid constructor/prototype paradigm of object definition to show inheritance,
// Class Definition for SuperClass Polygon
function Polygon(sides)
{
this._sides = sides;
}
Polygon.prototype.GetArea = function()
{
return 0;
}
// Class Definition for subclass Trigangle
function Trigangle(base, height)
{
Polygon.call(this, 3); // triangel 's sides=3
this._base = base;
this._height = height;
}
Trigangle.prototype = new Polygon();
Trigangle.prototype.GetArea = function()
{
return 0.5 * this._base * this._height;
}
// Test Code
var tra = new Trigangle(12, 4);
alert(tra.GetArea());
alert(tra._sides);
// Example of Dynanuc prototying to show inheritance ( the purpose is to write all code including function inside of constructor)
// superclass
function Polygon1(iSides)
{
this.sides = iSides;
if (typeof Polygon1._initialized == "undefined")
{
Polygon1.prototype.getArea = function()
{
return 0;
};
Polygon1._initialized = true;
}
}
// subclass
function Triangle1(iBase, iHeight)
{
Polygon1.call(this, 3);
this.base = iBase;
this.height = iHeight;
if (typeof Triangle1._initialized == "undefined")
{
Triangle1.prototype.getArea = function()
{
return 0.5 * this.base * this.height;
};
Triangle1._initialized = true;
}
}
Triangle1.prototype = new Polygon1();
// Test
var tra1 = new Triangle1(12, 4);
alert(tra1.getArea());
alert(tra1.sides);
// By using xbObjects for oop in javascript
// need to reference a js file called xbObjects.js
// super class
_classes.registerClass("Polygon2");
function Polygon2(iSides)
{
_classes.defineClass("Polygon2", prototypeFunction);
this.init(iSides);
function prototypeFunction()
{
Polygon2.prototype.init = function(iSides)
{
this.parentMethod("init");
this.sides = iSides;
};
Polygon2.prototype.getArea = function()
{
return 0;
};
}
}
// subclass
_classes.registerClass("Triangle2", "Polygon2");
function Triangle2(iBase, iHeight)
{
_classes.defineClass("Triangle2", prototypeFunction);
this.init(iBase, iHeight);
function prototypeFunction()
{
Triangle2.prototype.init = function(iBase, iHeight)
{
this.parentMethod("init", 3);
this.base = iBase;
this.height = iHeight;
};
Triangle2.prototype.getArea = function()
{
return 0.5 * this.base * this.height;
};
}
}
// test
var tra2 = new Triangle2(12, 4);
alert(tra2.getArea());
</script>
</head>
<body>
</body>
</html>
BOM of Javascript