I am creating two classes, Rectangle and Square, based on the example shown on MDN.
Since Rectangle is the prototype of Square, they share the same method area().
However, I want area() to run only if length === height for the square.
I’ve tried to add an if-statement after super(), but it area() still returns this.length* this.height regardless of an erroneous input.
I could add an if-statement in the area() method, but I did not because it would not make sense when we are calculating the area of a rectangle.
class Rectangle {
constructor(length, height){
this.length = length;
this.height = height;
}
area(){
return this.length*this.height;
}
}
class Square extends Rectangle {
constructor(length, height){ // have area() return "Not a square" instead of a number
super(length, height);
if (length !== height) {
console.log("Not a square.")
}
this.name = "square";
}
}
const rectangle = new Rectangle(2,3);
console.log(rectangle.area());
const square = new Square(5,2);
console.log(square.area())
>Solution :
an idea can be to overload area method in rectlangle to only call rectangle method when length === height
area() {
return (this.length === this.height) ? super.area() : undefined;
}
class Rectangle {
constructor(length, height){
this.length = length;
this.height = height;
}
area(){
return this.length*this.height;
}
}
class Square extends Rectangle {
constructor(length, height){ // have area() return "Not a square" instead of a number
super(length, height);
if (length !== height) {
console.log("Not a square.")
}
this.name = "square";
}
area(){
return (this.length === this.height) ? super.area() : undefined;
}
}
const rectangle = new Rectangle(2,3);
console.log(rectangle.area());
const square = new Square(5,2);
console.log(square.area())