一个能随机生成Circle类和Triangle类对象的静态方法
时间: 2024-03-25 20:37:10 浏览: 29
好的,以下是一个能随机生成Circle类和Triangle类对象的静态方法:
```javascript
class Circle {
constructor(radius) {
this.radius = radius;
}
get area() {
return Math.PI * this.radius ** 2;
}
}
class Triangle {
constructor(base, height) {
this.base = base;
this.height = height;
}
get area() {
return this.base * this.height / 2;
}
}
class ShapeGenerator {
static generate() {
const randomNum = Math.random();
if (randomNum < 0.5) {
const radius = Math.floor(Math.random() * 10) + 1;
return new Circle(radius);
} else {
const base = Math.floor(Math.random() * 10) + 1;
const height = Math.floor(Math.random() * 10) + 1;
return new Triangle(base, height);
}
}
}
```
这个静态方法 `generate` 可以随机生成一个 Circle 类或 Triangle 类的对象。如果随机数小于 0.5,则生成一个 Circle 对象,否则生成一个 Triangle 对象。生成 Circle 对象时,随机生成一个半径,生成 Triangle 对象时,随机生成一个底边和高。