在ES6中,super()方法用于调用父类的构造函数。它必须在子类的构造函数中调用super(),以便可以在子类中访问父类的属性和方法。
当调用super()时,它会返回一个指向父类的实例,因此可以使用super关键字来访问父类的成员。
例如,假设有一个父类叫做Animal,它有一个属性叫做name和一个方法叫做speak。然后我们创建一个子类叫做Dog,它继承自Animal类。在子类的构造函数中,我们可以使用super()来调用父类的构造函数,以便可以在子类中访问父类的属性和方法。
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
super.speak();
console.log(`${this.name} is a ${this.breed}.`);
}
}
const myDog = new Dog('Max', 'Labrador');
myDog.speak();
在上面的例子中,我们首先定义了一个Animal类,它有一个构造函数和一个speak方法。然后我们定义了一个Dog类,它继承自Animal类。在Dog类的构造函数中,我们调用了super(name),这样就将name传递给了父类的构造函数进行初始化。然后我们定义了一个speak方法,通过使用super.speak()来调用父类的speak方法,并在子类中添加了一些额外的功能。
通过使用super()方法,我们可以在子类中使用父类的属性和方法,从而实现了继承和扩展。