OO – Inheritance Helper

by Shane Porter

JavaScript

// nice little helper stolen from node.js to make things easier
function inherits(ctor, superCtor) {
    ctor.prototype = Object.create(superCtor.prototype, {
        constructor: {
            value: ctor,
            enumerable: false,
            writable: true,
            configurable: true
        },
        super: {
            value: superCtor,
            enumerable: false,
            writable: true,
            configurable: true
        }
    });
}

// our "parent" constructor
function Shape() {
    // convert passed in arguments to an array of sides
    this.sides = Array.prototype.slice.apply(arguments);
};

// our "child" constructor
function Square(a, b, c, d) {
    // call our parent's constructor
    this.super.call(this, a, b, c, d);
};
inherits(Square, Shape); // note we do this before augmenting the prototype
Square.prototype.area = function () {
    return this.sides[0] * this.sides[1];
};

var square1 = new Square(4, 4, 4, 4);

console.log(square1);
console.log('Square area:', square1.area());

function Circle(circumference) {
    this.super.call(this, circumference);
    this.diameter = circumference / Math.PI;
    this.radius = this.diameter / 2;
};
inherits(Circle, Shape);
Circle.prototype.area = function () {
    return Math.pow(this.radius, 2) * Math.PI;
};

var circle1 = new Circle(4);

console.log(circle1);
console.log('Circle area:', circle1.area());

function Triangle(a, b, c) {
    this.super.call(this, a, b, c);
    this.halfPerimeter = (a + b + c) / 2;
};
inherits(Triangle, Shape);
Triangle.prototype.area = function () {
    // heron's forumula
    return Math.sqrt(
    this.halfPerimeter * (this.halfPerimeter - this.sides[0]) * (this.halfPerimeter - this.sides[1]) * (this.halfPerimeter - this.sides[2]));
};

var triangle1 = new Triangle(4, 4, 4);

console.log(triangle1);
console.log('Triangle area:', triangle1.area());