Curious Coder
Curious Coder

Reputation: 1

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.

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())

Upvotes: 0

Views: 52

Answers (1)

yadejo
yadejo

Reputation: 1968

You can throw an error when the criteria is not matched. This will stop the construction of the object.

class Square extends Rectangle {
  constructor(length, height){ 
    super(length, height);
    if (length !== height) {
      throw new Error("not a square");
    }
    this.name = "square";
  }
}

... 


try {
  const notASquare = new Square(10,20); // This will throw an error
} catch(e) {
  console.log(e)
}

However

in this case i think it makes more sence to only accept 1 parameter to prevent this error from happening:

class Square extends Rectangle {
  constructor(size) {
    super(size, size); // Passing size 2 times makes sure length and height for a square are always equal
    this.name = "square";
  }
}

Upvotes: 3

Related Questions