Home > database >  how to call a static method from another class in JS
how to call a static method from another class in JS

Time:08-12

I need to calculate the area of 3 classes ( Square, rectangular, circle), with only 1 static method inside the class AreaCalculator . How can I achieve that?

  class Square {
  
  constructor(side) {
    this.sides = side;
  }
}

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
}

class Circle {

  constructor(radius) {
    this.radius = radius;
  }
}

class AreaCalculator {
  // ... static method to implement

}

const square = new Square(4);
const rectangle = new Rectangle(4, 2);
const circle = new Circle(5);

console.log(AreaCalculator.calculate(square));
console.log(AreaCalculator.calculate(rectangle));
console.log(AreaCalculator.calculate(circle));

CodePudding user response:

Something like this?

static calculate(shape) {
        switch (shape.constructor.name) {
            case "Square": return shape.sides * shape.sides;
            case "Circle": return Math.PI * shape.radius * shape.radius;
            case "Rectangle": return shape.width * shape.height;
        }
    }
  • Related