- 示例代码:
// 定义父类
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
// 定义子类,继承自Animal
class Dog extends Animal {
constructor(name, breed) {
// 调用父类的constructor方法
super(name);
this.breed = breed;
}
bark() {
console.log(`${this.name} (${this.breed}) barks.`);
}
}
// 创建一个Dog实例
const myDog = new Dog('Buddy', 'Golden Retriever');
myDog.speak();
myDog.bark();
super
关键字的作用:
- 在子类的构造函数中,
super
用于调用父类的构造函数,以初始化从父类继承来的属性。在调用super
之前,this
关键字是不能在子类构造函数中使用的,因为子类实例还没有被正确初始化。
- 在子类的方法中,
super
还可以用来调用父类的方法,这样可以在子类方法中复用父类的功能,然后根据需要进行扩展。例如,如果在Dog
类中重写speak
方法,并且还想保留父类speak
方法的部分功能,就可以使用super.speak()
。