[英]how to call a static method from another class in JS
我需要計算 3 個類(正方形、矩形、圓形)的面積,在class AreaCalculator
中只有 1 個 static 方法。 我怎樣才能做到這一點?
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));
像這樣的東西?
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.