添加到 class 原型的方法是否在继承 class 中可用?

Is a method added to prototype of class available in inherited class?

我是 Javascript 的新手,几天前才开始使用。我在练习的时候遇到了一个问题,虽然我做了很多研究还是没有搞定。

我得到以下矩形 class 定义

class Rectangle {
    constructor(w, h) {
        this.w = w;
        this.h = h;
    }
}

我被要求通过原型设计添加方法 area(),我做了以下操作:

Rectangle.prototype.area = function(){
    return this.w * this.h;
}

如果我为方形 class 继承矩形 class,方形 class 的实例是否继承通过原型添加的 area() 方法?像这样?

class Square extends Rectangle{
    constructor(w, h){
        super(w, h);
    }
} 

鉴于上面的以下代码,是否可以或如何从 Square 实例调用方法 area() 以便以下代码有效?

const sqr = new Square(3);   
console.log(sqr.area());

如果你熟悉其他语言,有什么原型可以与Java、Kotlin等其他语言相比?

您的 Square class 的构造函数中存在问题。它应该只接受一个参数。

改正后,它工作正常:

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) {
    super(w, w);
  }
}

console.log(new Square(2).area());

对于你问题的第二部分:

If you are familiar with other languages, what prototyping can be compared to other languages such as Java, Kotlin and etc?

我认为this answer很好地总结了class实体继承(例如Java)和原型继承(例如Java脚本)之间的区别。