Your example could make more use of inheritance. The Shape
class should have all three properties and the Square
class’ constructor should only take the sideLength
parameter and then call super()
with the necessary data.
To help you out a bit here’s the finished Shape
class and the code to test it You’ll need to only add code in the Square
class:
class Shape {
name;
sides;
sideLength;
constructor(name, sides, sideLength) {
this.name = name;
this.sides = sides;
this.sideLength = sideLength;
}
calcPerimeter() {
console.log(`The ${ this.name }'s perimeter length is ${ this.sides * this.sideLength }.`);
}
}
class Square extends Shape {
/* Your code goes here */
}
const square = new Square(4);
square.calcPerimeter();
square.calcArea();
Let me know if you need any more help.
Michael
Hi Michael, I genuinely appreciate your feedback. The code has been updated. Kindly check to see whether there is an improvement.
I anticipate your response
You’re welcome!
Two things remain:
- Since we already assign
sideLength
in theShape
constructor, we can simply add it as third parameter to thesuper()
call. (Variables are allowed there.) - The area calculation is wrong. You get the area of a square by multiplying its side length with itself. There are different ways to achieve this in JavaScript. Can you find out one or more?
The code has been updated, is it correct now?
The area calculation is right
But you removed to much around the constructor. We still want to have the ability to choose the length of the side with:
const square = new Square(5); /* <-- any number should be possible */
Solution for the constructor
constructor(sidesLength) { super("square", 4, sidesLength) }I cannot thank you well enough. I am so grateful for taking out time to respond.
I don’t mind personal mentorship from you.
Thank you for the kind words. It was a pleasure to help you.
Come back whenever you have more questions or exercises.