I have a method toString() which is not being inherited from Shape. Why?
function Shape(){
this.name = 'shape';
this.toString = function() {return this.name;};
}
function TwoDShape(){
this.name = '2D shape';
}
function Triangle(side, height) {
this.name = 'Triangle';
this.side = side;
this.height = height;
this.getArea = function(){return this.side * this.height / 2;};
}
TwoDShape.prototype = TwoDShape;
Triangle.prototype = Triangle;
TwoDShape.prototype.constructor = TwoDShape;
Triangle.prototype.constructor = Triangle;
var my = new Triangle(5, 10);
document.write("my getarea: " + my.getArea() + "my name is: " + my.toString() + "<br>");
Triangle‘s prototype must be aShapeso that it inherits its methods:More specifically, since you have multiple levels of inheritance:
That is,
TwoDShapeinheritsShape, andTriangleinherits fromTwoDShape.Generically, if
FooinheritsBar, you’d have:DEMO.
References: