gpt4 book ai didi

javascript - 继承 toString()

转载 作者:行者123 更新时间:2023-11-28 16:12:18 26 4
gpt4 key购买 nike

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

Demo jsFiddle.

最佳答案

Triangle 的原型(prototype)必须是 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

引用文献:

关于javascript - 继承 toString(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12492469/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com