Inheritance: 5-Uber—Access to the Parent from a Child Object
by creativevilla
JavaScript
// Uber—Access to the Parent from a Child Object
function Shape() {
// Empty constructor
}
// Augementing prototype
Shape.prototype.name = "Shape";
Shape.prototype.toString = function () {
console.log(this.constructor.uber);
var result = [];
if (this.constructor.uber) {
result[result.length] = this.constructor.uber.toString();
}
result[result.length] = this.name;
console.log(result);
return result.join(', ');
};
function TwoDShape() {
// Empty constructor
}
// Take care of inheritance
var F = function () {
// Empty constructor
};
F.prototype = Shape.prototype;
TwoDShape.prototype = new F();
TwoDShape.prototype.constructor = TwoDShape;
TwoDShape.uber = Shape.prototype; // new line
// Augementing prototype
TwoDShape.prototype.name = "2D Shape";
function Triangle(size, height) {
this.size = size;
this.height = height;
}
// Take care of inheritance
var F = function () {
// Empty constructor
};
F.prototype = TwoDShape.prototype;
Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;
Triangle.uber = TwoDShape.prototype; // new line
// 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
var s = new Shape();
console.log(s.name); // Shape