Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How so I stop a shared method from running with class and extends?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading