- 在子类构造函数中:
- 作用:在子类构造函数中,
super
用于调用父类的构造函数,目的是初始化继承自父类的实例属性。在使用this
关键字之前,必须先调用super
。因为子类的this
对象是基于父类的构造函数初始化后创建的。
- 示例:
class Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // 调用父类Animal的构造函数,初始化name属性
this.breed = breed;
}
}
const myDog = new Dog('Buddy', 'Golden Retriever');
console.log(myDog.name); // 'Buddy'
console.log(myDog.breed); // 'Golden Retriever'
- 在子类普通方法中:
- 作用:在子类普通方法中,
super
用于访问和调用父类的方法。这使得子类可以复用父类的方法,并且可以在其基础上进行扩展。
- 示例:
class Animal {
speak() {
return 'I am an animal';
}
}
class Dog extends Animal {
speak() {
const parentSpeak = super.speak(); // 调用父类的speak方法
return `${parentSpeak} and I am a dog`;
}
}
const myDog = new Dog();
console.log(myDog.speak());
// 'I am an animal and I am a dog'
- 不遵循规则的问题:
- 在构造函数中不先调用super:
- 问题:如果在子类构造函数中使用
this
之前没有调用super
,会抛出ReferenceError
。因为this
在子类构造函数中只有在super
调用之后才被正确初始化。
- 示例:
class Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
constructor(name, breed) {
this.breed = breed; // 报错,在使用this前未调用super
super(name);
}
}
// 会抛出ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
- 在普通方法中错误使用super:
- 问题:如果在非方法的函数(如箭头函数)内使用
super
,会抛出SyntaxError
,因为箭头函数没有自己的this
和super
绑定,它们从包含它们的词法环境中继承这些绑定。
- 示例:
class Animal {
speak() {
return 'I am an animal';
}
}
class Dog extends Animal {
speak = () => {
const parentSpeak = super.speak(); // 报错,箭头函数内不能使用super
return `${parentSpeak} and I am a dog`;
}
}
// 会抛出SyntaxError: 'super' keyword unexpected here