0

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?

Farruh Habibullaev
  • 2,342
  • 1
  • 26
  • 33
  • 1
    @RobbyCornelissen, I have tried. It is not working. I will edit to make it more clear. I was supposed to say "How to make it work?" I will edit the question. Sorry. – Farruh Habibullaev Feb 04 '20 at 04:36
  • A square only has one measurement for all its side lengths, you're trying to pass `h` into the `super()`, but only pass `w` it into your `Square()` constructor – Nick Parsons Feb 04 '20 at 04:40
  • *"I am asked to add the method area() through prototyping"* Defining an `area() {}` method inside the `class {}` body achieves exactly the same runtime result, just with different syntax. If you use `class` you shouldn't have to reference `X.prototype` directly. – Felix Kling Feb 04 '20 at 09:59

1 Answers1

4

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.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156