使用 super
本课属于 Coddy JavaScript 学习旅程的“面向对象编程”单元。第 37 课,共 56 课。
重写方法时,你仍然可以使用 super.methodName() 访问父类的原始版本。这样,你就可以扩展或修改父类的行为,而不是完全替换它。
创建一个包含方法的父类:
class Animal {
makeSound() {
return "Generic animal sound";
}
}创建一个继承父类的子类:
class Dog extends Animal {
makeSound() {
// 先调用父类的方法
const parentSound = super.makeSound();
// 然后添加更多功能
return `${parentSound}, but also Woof!`;
}
}创建一个子类的实例:
const myDog = new Dog();
console.log(myDog.makeSound());
// 输出:“Generic animal sound, but also Woof!”super 关键字让你可以调用父类的方法,同时在子类中添加自己的功能。
挑战
给你一个带有 calculateArea() 方法的 Shape 类,以及一个继承自它的 Rectangle 类。你的任务是使用 super 在 Rectangle 中重写 calculateArea() 方法。
你的任务是完成 Rectangle 类中的 calculateArea() 方法,以便:
- 使用
super调用父类的calculateArea()方法,并保存结果 - 计算矩形的实际面积:
width × height - 返回一个组合字符串:父类的消息 + 矩形面积。示例:
Calculating area... Rectangle area: 50
亲手试试
import { Shape } from './shapes.js';
import { Rectangle } from './shapes.js';
// 测试代码,请勿修改
const rectangle = new Rectangle(5, 10);
console.log(rectangle.calculateArea()); // 预期输出:“Calculating area... Rectangle area: 50”
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向对象编程中的所有课
8整理 OOP 代码
将类组织到模块中自己练习: JavaScript 在线编译器