i am trying to figure out how the code below works. Can somebody explain what does it mean when it says ” create an uber property that points to the parent’s prototype object.” What exactly does it mean when it says “this.constructor.uber” points to parent’s prototype? i’ve been scratching my head for a while now. i would be really thankful if somebody could explain what’s happening in function Shape().
function Shape() {}
// augment 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() {}
// take care of inheritance
var F = function () {};
F.prototype = Shape.prototype;
TwoDShape.prototype = new F();
TwoDShape.prototype.constructor = TwoDShape;
TwoDShape.uber = Shape.prototype;
// augment prototype
TwoDShape.prototype.name = '2D shape';
function Triangle(side, height) {
this.side = side;
this.height = height;
}
// take care of inheritance
var F = function () {};
F.prototype = TwoDShape.prototype;
Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;
Triangle.uber = TwoDShape.prototype;
// augment prototype
Triangle.prototype.name = 'Triangle';
Triangle.prototype.getArea = function () {
return this.side * this.height / 2;
}
var my = new Triangle(5, 10);
my.toString()
Output: "shape,2Dshape,Triangle"
In Javascript inheritance, there is no support for accessing a
supermethod, so what I can see here with uber, is having access to its parent methods.Name it parent as following:
TwoDShape.parent = Shape.prototypeThat way you can have direct access to a parent property:
TwoDShape.parent.nameshould return'shape'.What
toString()is actually doing here, is:Note that I changed the
ubertoparentso its more readable. the first assignment of result will always be 0, so it was not necessary the call toresult.length.What the calls would return for each object?:
Shape.toString();:'shape'(there’s no parent)TwoDShape.toString();:'shape, 2D shape'('shape'for the call toShape.toString();, and'2D shape'for its own name, joined).Triangle.toString();:'shape, 2D shape, Triangle'('shape, 2D shape'for the call toTwoDShape.toString();, and'Triangle'for its own name, joined).