Inheritance: 1-Prototype Chaining Example

by creativevilla

JavaScript

// Prototype Chaining Example
function Shape() {
    this.name = "Shape";
    this.toString = function () {
        return this.name;
    }
}

function TwoDShape() {
    this.name = "2D Shape";
}

function Triangle(size, height) {
    this.name = "Triangle";
    this.size = size;
    this.height = height;
    this.getArea = function () {
        return this.size * this.height / 2;
    }
}

// Inheritance
TwoDShape.prototype = new Shape();
TwoDShape.prototype.constructor = TwoDShape;
Triangle.prototype = new TwoDShape();
Triangle.prototype.constructor = Triangle;

var t = new Triangle(5, 10);

console.log(t.toString()); // Triangle
console.log(t.getArea()); // 25
console.log(t instanceof Triangle); // true
console.log(t instanceof TwoDShape); // true
console.log(t instanceof Shape); // true
console.log(t instanceof Array); // false

var s = new Shape();
console.log(s.name); // Shape