Inheritance: 2-Moving Shared Properties to the Prototype
by creativevilla
JavaScript
// Inheritance: Seperating properties which needs to be inherited
function Shape() {
// Empty constructor
}
// Augmenting properties and methods
Shape.prototype.name = "Shape";
Shape.prototype.toString = function () {
return this.name;
}
function TwoDShape() {
// Empty constructor
}
// Taking care of inheritance
TwoDShape.prototype = new Shape();
TwoDShape.prototype.constructor = TwoDShape;
// Augmenting properties
TwoDShape.prototype.name = "2D Shape";
function Triangle(size, height) {
this.size = size;
this.height = height;
}
// Taking care of inheritance
Triangle.prototype = new TwoDShape();
Triangle.prototype.constructor = Triangle;
// Augmenting properties and methods
Triangle.prototype.name = "Triangle";
Triangle.prototype.getArea = function () {
return this.size * this.height / 2;
}
var t2 = new Triangle(5, 10);
console.log(t2.toString()); // Triangle
console.log(t2.getArea()); // 25
console.log(t2 instanceof Triangle); // true
console.log(t2 instanceof TwoDShape); // true
console.log(t2 instanceof Shape); // true
console.log(t2 instanceof Array); // false
var s = new Shape();
console.log(s.name); // Shape