Inheritance: 4-A Temporary Constructor—new F()

by creativevilla

JavaScript

// 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":

//-----------------------------------------------------------------------------------------------------------------//

// Solution to previous code

// Inheritance: A Temporary Constructor—new F()

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
function F() {
    // Empty temp constructor
}
F.prototype = Shape.prototype;
TwoDShape.prototype = new F();
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
function F() {
    // Empty temp constructor
}
F.prototype = TwoDShape.prototype;
Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;

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

var t4 = new Triangle(5, 10);

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

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