Reputation: 13
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"
Upvotes: 1
Views: 457
Reputation: 380
In Javascript inheritance, there is no support for accessing a super
method, so what I can see here with uber, is having access to its parent methods.
Name it parent as following:
TwoDShape.parent = Shape.prototype
That way you can have direct access to a parent property: TwoDShape.parent.name
should return 'shape'
.
What toString()
is actually doing here, is:
var result = []; //declare an array
if (this.constructor.parent) { //if there is a parent prototype
result[0] = this.constructor.parent.toString(); //set the 0 position of result with the return value of parent's toString() method.
}
result[result.length] = this.name; //set the position (0 or 1, if we had a parent it will be 1, otherwise 0) with the current name.
return result.join(', '); //return the names joined with a comma
Note that I changed the uber
to parent
so its more readable. the first assignment of result will always be 0, so it was not necessary the call to result.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 to Shape.toString();
, and '2D shape'
for its own name, joined).
Triangle.toString();
: 'shape, 2D shape, Triangle'
('shape, 2D shape'
for the call to TwoDShape.toString();
, and 'Triangle'
for its own name, joined).
Upvotes: 1