重写与面积方法
本课属于 Coddy JavaScript 学习旅程的“面向对象编程”单元。第 41 课,共 56 课。
挑战
通过重写 Circle 类的 describe() 方法并添加新的 calculateArea() 方法来改进这个类。
你的任务:
重写
describe()方法,使其返回${super.describe()} (Circle with radius ${this.radius})。示例:“A blue shape (Circle with radius 10)”
- 添加一个
calculateArea()方法,该方法: - 使用公式
Math.PI * this.radius * this.radius计算面积 返回计算出的面积(无需使用 console.log)
*这是 Circle 专属的方法(不在父类 Shape 中)
亲手试试
import { Shape } from './Shape.js';
import { Circle } from './Circle.js';
// 测试
const basicShape = new Shape('red');
console.log(basicShape.describe()); // "A red shape"
const myCircle = new Circle('blue', 10);
console.log(myCircle.describe()); // 应输出:“A blue shape (Circle with radius 10)”
console.log(myCircle.calculateArea()); // 应输出:“314.1592653589793”面向对象编程中的所有课
8整理 OOP 代码
将类组织到模块中自己练习: JavaScript 在线编译器