Inheritance: 3-Inheriting the Prototype Only

by creativevilla

JavaScript

// Inheritance: Inheriting the Prototype Only

function Shape() {
    // Empty constructor    
}

// Augmenting prototype
Shape.prototype.name = "Shape";
Shape.prototype.toString = function () {
    return this.name;
};

function TwoDShape() {
    // Empty constructor    
}

// Take care of inheritance
TwoDShape.prototype = Shape.prototype;
TwoDShape.prototype.constructor = TwoDShape;

// Augmenting prototype
TwoDShape.prototype.name = "2D Shape";

function Triangle(size, height) {
    this.size = size;
    this.height = height;
}

// Take care of inheritance
Triangle.prototype = TwoDShape.prototype;
Triangle.prototype.constructor = Triangle;

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

var t3 = new Triangle(5, 10);

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

// Simply copying the prototype is more efficient but it has a side effect: because all of the children and parents point to the same object, when a child modifies the prototype, the parents get the changes, and so do the siblings.

// Triangle.prototype.name = 'Triangle';

// Above line  changes the name property, so it effectively changes Shape.prototype.name too. If you create an instance using new Shape(), its name property will say "Triangle":

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