// 父类 Animal:所有动物的通用属性和方法
class Animal{
constructor(name, age){
this.name = name; // 每个动物都有名字
this.age = age; // 每个动物都有年龄
}
// 父类通用方法:移动
move(speed){
console.log(`the ${this.name} moves at a speed of ${speed}mph`)
}
}
//-----------------------------------------------------------------------
// 子类 Rabbit,继承 Animal
class Rabbit extends Animal{
constructor(name, age, runSpeed){
super(name, age); // 调用父类构造函数,初始化 name 和 age
this.runSpeed = runSpeed; // 子类独有的属性:奔跑速度
}
// 子类方法:奔跑
run(){
console.log(`this ${this.name} can run`);
// 调用父类的 move 方法,复用逻辑
super.move(this.runSpeed);
}
}
// 子类 Fish,继承 Animal
class Fish extends Animal{
constructor(name, age, swimSpeed){
super(name, age); // 初始化 name 和 age
this.swimSpeed = swimSpeed; // 子类独有的属性:游泳速度
}
// 子类方法:游泳
swim(){
console.log(`this ${this.name} can swim`)
super.move(this.swimSpeed); // 调用父类的 move 方法
}
}
// 创建对象
const rabbit = new Rabbit("rabbit", 1, 25);
const fish = new Fish("fish", 1, 25);
// 测试对象属性
console.log(fish.swimSpeed); // 25,子类独有属性
console.log(fish.name); // "fish",继承自父类
console.log(rabbit.runSpeed);// 25,子类独有属性
// 调用子类方法 + 父类方法
rabbit.run(); // 子类方法 -> "this rabbit can run"
// 父类方法 -> "the rabbit moves at a speed of 25mph"
rabbit.move(); // 直接调用父类方法 (未传 speed 参数,会输出 undefined)
fish.swim(); // 子类方法 -> "this fish can swim"
// 父类方法 -> "the fish moves at a speed of 25mph"
- 继承 (extends)
- 子类自动继承父类的属性和方法。
- 让代码更简洁,避免重复写相同逻辑。
- super() 用法
- 在 constructor 里:调用父类构造函数,初始化父类属性。
- 在方法里:调用父类的方法,复用逻辑。
- 多态
- 父类有一个通用方法 move(speed)。
- 不同子类实现自己的动作(run、swim、fly),再调用 super.move() 来复用逻辑。
- 这就是 多态 (polymorphism) 的体现。