我有一个方法toString()
,它不会从Shape
继承。为什么呢?
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>");
答案 0 :(得分:3)
Triangle
的原型必须是Shape
才能继承其方法:
Triangle.prototype = new Shape();
更具体地说,因为你有多个级别的继承:
TwoDShape.prototype = new Shape();
TwoDShape.prototype.constructor = TwoDShape;
Triangle.prototype = new TwoDShape();
Triangle.prototype.constructor = Triangle;
也就是说,TwoDShape
继承Shape
,而Triangle
继承自TwoDShape
。
通常,如果Foo
继承Bar
,您就会:
Foo.prototype = new Bar(); // inherit Bar
Foo.prototype.constructor = Foo; // Fix constructor which now points to Bar
<强> DEMO 强>
答案 1 :(得分:1)
你必须将阴影的原型设置为Shade,而不是像你一样设置为TwoDS形或三角形。
答案 2 :(得分:0)
原型继承应该是SubConstructor.prototype = new ParentConstructor
,而不是SubConstructor.prototype = ParentConstructor
。您没有正确继承原型,因此您不会继承toString
方法; getArea
不是原型方法,而是每个实例的实际属性,因此它可以工作。