【问题标题】:Does Child Class Inherited their parent class prototype in the following example (JS)下例中子类是否继承了父类原型(JS)
【发布时间】: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


【解决方案1】:

由于Square 构造函数将只用一个参数调用(因为它的大小在所有方面都相等),您需要将其“转换”为需要 2 个参数(宽度和高度)的Rectangle 构造函数调用.由于正方形的两个参数相等,因此您需要将该单个参数两次传递给 Rectangle 构造函数:

class Rectangle {
    constructor(w, h) {
        this.w = w;
        this.h = h;
    }
    area() { // Use this notation for prototype methods
        return this.w * this.h;  
    }
};

class Square extends Rectangle {
    constructor(w) { // One argument...
        super(w, w); // ...Two arguments, but width == height
    }
}

let square = new Square(10);
console.log(square.area());

【讨论】:

  • 我能够通过这样做来解决它:java class Square extends Rectangle { constructor(w, h) { super(w, h); this.w = w; this.h = w; } } 为什么这样有效?你的新 area() 符号也等于我写的那个吗?
  • 这也可以,但很遗憾您首先设置了this.h 错误(通过使用未定义的第二个参数调用super),并且那么必须通过对this.wthis.h的另一个分配来纠正该错误...我看不出你为什么要这样做的充分理由。
  • 是的,新的area() 符号等于你的。从 ECMAScript 2015 开始,这是您充分使用 class 表示法的方式。
猜你喜欢
  • 2011-08-28
  • 1970-01-01
  • 2015-04-17
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多