Inheritance: 6-Isolating the Inheritance Part into a Function
by creativevilla
JavaScript
// Isolating the Inheritance Part into a Function
function extend(Child, Parent) {
var F = function() { };
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.uber = Parent.prototype;
}
function Shape() {
// Empty constructor
}
// Augementing prototype
Shape.prototype.name = "Shape";
Shape.prototype.toString = function () {
var result = [];
if (this.constructor.uber) {
result[result.length] = this.constructor.uber.toString();
}
result[result.length] = this.name;
return result.join(', ');
};
function TwoDShape() {
// Empty constructor
}
// Take care of inheritance
extend(TwoDShape, Shape);
// Augementing prototype
TwoDShape.prototype.name = "2D Shape";
function Triangle(size, height) {
this.size = size;
this.height = height;
}
// Take care of inheritance
extend(Triangle, TwoDShape);
// Augementing prototype
Triangle.prototype.name = "Triangle";
Triangle.prototype.getArea = function () {
return this.size * this.height / 2;
};
var t5 = new Triangle(5, 10);
console.log(t5.toString()); // Triangle
console.log(t5.getArea()); // 25
console.log(t5 instanceof Triangle); // true
console.log(t5 instanceof TwoDShape); // true
console.log(t5 instanceof Shape); // true
console.log(t5 instanceof Array); // false