Object Oriented JavaScript Tutorial

< html>

Example



function Shape(iSides) {
    this.sides  = iSides;
    if (typeof Shape._initialized == "undefined") {
        Shape.prototype.getArea = function () {
            return 0;
        };
        Shape._initialized = true;
    }
}
function Triangle(iBase, iHeight) {
    Shape.call(this, 3);
    this.base = iBase;
    this.height = iHeight;
    if (typeof Triangle._initialized == "undefined") {
        Triangle.prototype.getArea = function () {
            return 0.5 * this.base * this.height;
        };
        Triangle._initialized = true;
    }
}
Triangle.prototype = new Shape();
function Rectangle(iLength, iWidth) {
    Shape.call(this, 4);
    this.length = iLength;
    this.width = iWidth;
    if (typeof Rectangle._initialized == "undefined") {
        Rectangle.prototype.getArea = function () {
            return this.length * this.width;
        };
        Rectangle._initialized = true;
    }
}
Rectangle.prototype = new Shape();
var triangle = new Triangle(12, 4);
var rectangle = new Rectangle(22, 10);
document.write("triangle.sides:"+triangle.sides);
document.write("
");
document.write("triangle.getArea():"+triangle.getArea());
document.write("
");
document.write("rectangle.sides:"+rectangle.sides);
document.write("
");
document.write("rectangle.getArea():"+rectangle.getArea());