简体   繁体   中英

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

the follwoing code:

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

Do I have problems with my inheritance?

I'm trying to use:

const rec = new Rectangle(3, 4);

const sqr = new Square(3);

console.log(rec.area());

console.log(sqr.area());

rec prints the correct answer but sqr print's out: NaN

I also tried maybe adding a Square prototype:

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

but the output is:

-1  
-1 

so this also affected area for rec.area()

Since the Square constructor will be called with only one argument (since its size is equal at all sides), you need to "translate" this to a Rectangle constructor call that needs 2 arguments (width and height). Since both are equal for the square, you need to pass that single argument twice to the Rectangle constructor:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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