Search code examples
javascriptinheritanceecmascript-6ecmascript-5

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


I am pretty new to Javascript and started a few days ago. 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 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:

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? 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?

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?


Solution

  • There's a problem in the constructor for your Square class. It should only accept one argument.

    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?

    I think this answer summarizes the differences between classical inheritance (e.g. Java) and prototypal inheritance (e.g. JavaScript) well.