I am confused a little bit with this simple snippet of code. I am not very familiar with prototype and still confused after watching a few videos and reading up on the subject.
In my understanding, we are creating a class Rectangle, that has a constructor. We are then creating
a function area which is a prototype of Rectangle.
then we are creating Square that inherits the properties of Rectangle. the problem is these two lines:
constructor(s) {
super(s, s);
I guess my question is why are we using both constructor(s) and super(s, s). I thought the super() job was to call the parent's constructor.
If the constructor is calling Rectangle's constructor why isn't requiring two variables for height and width?
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(s) {
super(s, s);
}
}
const rec = new Rectangle(3, 4);
const sqr = new Square(3);
console.log(rec.area());
console.log(sqr.area());
constructor(s) { … }does declare a single parametersfor theSquareconstructor,super(s, s)passes two arguments to the parentRectangleconstructor. Are you confused by the lack of indentation?super()call.