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());
You can't call super() outside of the child's constructor, because super(), like a constructor, is only used when you first initially create an instance of that object.
So in your example:
Square is only taking in 1 argument, because a square is equal on both sides. Unlike a rectangle, which has unequal lengths compared to its height. Technically speaking, all squares are a rectangle, but thats besides the point.
This works because you can see in your square class:
class Square extends Rectangle {
constructor(s) {
super(s, s);
}
Square is taking in s, which in this example is 3. Since the parent class Rectangle takes in an argument to define the width & the height, the Square is calling the Rectangle constructor and passing in 3 for the width & the height. Again, this is because a square has equal widths and height.
You don't have to pass an argument to the constructor, to call the super. You can do this:
class Square extends Rectangle {
constructor() {
super(3, 3);
}
But this would be bad practice, because you're not making this Square class reusable.
A prototype is a way for classes to inherit methods from others.
For example, we have the String prototype. A prototype comes with various methods.
const str = "hello world"
Here we define a string called str. Since str is a string, it is able to use the methods defined in the String prototype.
console.log(str.length)
Here we are using the method length defined in the String prototype, to get us the length of our string. Noticed how we never defined the method length anywhere? its inherited from the String prototype.