【发布时间】:2021-09-04 13:59:11
【问题描述】:
以下代码:
class Rectangle {
constructor(w, h) {
this.w = w;
this.h = h;
}
}
Rectangle.prototype.area = function () {
return (this.w * this.h);
};
class Square extends Rectangle {
constructor(w, h) {
super(w, h);
// this.w = w;
// this.h = h;
}
}
我的继承有问题吗?
我正在尝试使用:
const rec = new Rectangle(3, 4);
const sqr = new Square(3);
console.log(rec.area());
console.log(sqr.area());
rec 打印出正确答案,但 sqr 打印出来了:NaN
我也尝试过添加一个 Square 原型:
Square.prototype.area = function () {
return (this.w * this.w);
};
但输出是:
-1
-1
所以这也影响了rec.area()的区域
【问题讨论】:
-
Square 没有
h。 this.w * undefined 将是 NaN -
"我的继承有问题吗?" 在更高的级别上,您有the square-rectangle problem。但特别是在您的情况下,您只是没有设置
h。仅仅因为一个矩形有四个相等的边,并不意味着它没有高度。我只是说高度等于宽度。 -
@Tushar Shahi 仍然存在同样的问题,我在发布之前尝试过这个,我也试图以某种方式覆盖它,但父原型覆盖了我的 Square.prototype
-
编辑后,你有一个 Square 构造函数,它带有两个参数。但是你只传递一个论点。所以,
h隐含地是undefined。 -
让我给你最后一个提示 - 一个矩形有两对边,每边彼此相等。一个正方形,有四个相等的边,与
h = w相同。所以,如果你只得到一个边的长度,你如何构造一个矩形h = w? “*不确定当我扩展 Rec 时我是否也获得了 area 方法*”如果您没有该方法,则会收到无法调用它的错误。既然你可以调用它,它就在那里。
标签: javascript class oop inheritance prototype