首页 > 解决方案 > 下例中子类是否继承了父类原型(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()

标签: javascriptclassoopinheritanceprototype

解决方案


由于Square将仅使用一个参数调用构造函数(因为它的大小在所有方面都相等),因此您需要将其“转换”为Rectangle需要 2 个参数(宽度和高度)的构造函数调用。由于正方形都相等,因此您需要将该单个参数两次传递给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());


推荐阅读