0

我有一个方法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>");​

演示 jsFiddle。

4

3 回答 3

3

Triangle的原型必须是 aShape以便它继承其方法:

Triangle.prototype = new Shape();

更具体地说,因为您有多个继承级别:

TwoDShape.prototype = new Shape();
TwoDShape.prototype.constructor = TwoDShape;

Triangle.prototype = new TwoDShape();
Triangle.prototype.constructor = Triangle;

也就是说,TwoDShape继承ShapeTriangle继承自TwoDShape

通常,如果Foo继承Bar,您将拥有:

Foo.prototype = new Bar(); // inherit Bar
Foo.prototype.constructor = Foo; // Fix constructor which now points to Bar

演示

参考:

于 2012-09-19T10:05:10.337 回答
1

您必须将阴影的原型设置为 Shade,而不是像您那样设置为 TwoDShape 或 Triangle。

于 2012-09-19T10:04:02.360 回答
0

原型继承应该是SubConstructor.prototype = new ParentConstructor,不是SubConstructor.prototype = ParentConstructor。你没有正确继承原型,所以你没有继承toString方法;getArea不是原型方法,而是每个实例的实际属性,所以它可以工作。

于 2012-09-19T10:05:25.180 回答