简体   繁体   English

继承的class是否有添加到class原型的方法?

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

I am pretty new to Javascript and started a few days ago.我是 Javascript 的新手,几天前才开始使用。 When I was doing practice, I have encountered a problem, even though I did extensive research I did not still get it.我在练习的时候遇到了一个问题,虽然我做了很多研究还是没有搞定。

I am given the following Rectangle class definition我得到以下矩形 class 定义

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

I am asked to add the method area() through prototyping and I did the following:我被要求通过原型设计添加方法area() ,我做了以下事情:

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

And if I inherit the Rectangle class for Square class, does the square class's instance inherit area() method which is added through prototyping?如果我为 Square class 继承了 Rectangle class,那么 Square 类的实例是否继承了通过原型添加的area()方法? Like this?像这样?

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

Given the following code above, is it possible or how to call method area() from Square instance so that following code works?鉴于上面的以下代码,是否有可能或如何从 Square 实例调用方法area()以便以下代码有效?

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

If you are familiar with other languages, what prototyping can be compared to other languages such as Java, Kotlin and etc?如果您熟悉其他语言,那么什么原型可以与其他语言进行比较,例如 Java、Kotlin 等?

There's a problem in the constructor for your Square class. It should only accept one argument. Square class 的构造函数中存在问题。它应该只接受一个参数。

After correcting that, it works fine:更正后,它工作正常:

 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());

For the second part of your question:对于你问题的第二部分:

If you are familiar with other languages, what prototyping can be compared to other languages such as Java, Kotlin and etc?如果您熟悉其他语言,那么什么原型可以与其他语言进行比较,例如 Java、Kotlin 等?

I think this answer summarizes the differences between classical inheritance (eg Java) and prototypal inheritance (eg JavaScript) well.我认为这个答案很好地总结了经典 inheritance(例如 Java)和原型 inheritance(例如 JavaScript)之间的区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM