当扩展一个类并使用原类的属性时,你在super()里面放了什么?

问题描述 投票:0回答:1

我以为代码应该是这样的,但是却不能通过。

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;
     }
}

我以为使用super从原类中接收参数时,需要把它们放在新的构造函数中吗?但当我这样改变Square类时,它就通过了。 我不明白?

class Square extends Rectangle{
    constructor(s) {
        super(s)
        this.w = s;
        this.h = s;
     }
javascript class oop constructor prototype
1个回答
2
投票

你需要传递父构造函数所期望的参数,在你的例子中,你需要传递一个高度和一个宽度。如何获得这些值由你决定。对于一个正方形,为两个参数传递相同的值是有意义的。你不需要为两个参数分配 .w.h 身处 Square 构造函数,该 Rectangle 构造函数已经创建了这些属性。所以只需要

class Square extends Rectangle {
    constructor(s) {
        super(s, s)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.