下例中Child Class是否继承了parent class的原型(JS)

Does Child Class Inherited their parent class prototype in the following example (JS)

以下代码:

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 构造函数将仅使用一个参数调用(因为它的大小在所有方面都相等),您需要将其“翻译”为需要 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());