推荐答案
在 JavaScript 的类中,super 关键字用于调用父类的构造函数或访问父类的属性和方法。它主要有以下两种用途:
在构造函数中调用父类的构造函数:
当子类继承父类时,子类的构造函数中必须调用super(),以确保父类的构造函数被正确执行。super()必须在this关键字之前调用。在方法中访问父类的属性和方法:
在子类的方法中,可以通过super.methodName()或super.propertyName来调用父类的方法或访问父类的属性。
本题详细解读
1. 在构造函数中使用 super
在子类的构造函数中,super() 用于调用父类的构造函数。这是必须的,因为子类需要继承父类的属性和方法。如果不调用 super(),JavaScript 会抛出错误。
// www.javascriptcn.com code example
class Parent {
constructor(name) {
this.name = name;
}
}
class Child extends Parent {
constructor(name, age) {
super(name); // 调用父类的构造函数
this.age = age;
}
}
const child = new Child('Alice', 10);
console.log(child.name); // 输出: Alice
console.log(child.age); // 输出: 10在上面的例子中,Child 类继承了 Parent 类。在 Child 的构造函数中,super(name) 调用了 Parent 的构造函数,并将 name 参数传递给它。
2. 在方法中使用 super
在子类的方法中,super 可以用于调用父类的方法或访问父类的属性。这在子类需要扩展或覆盖父类方法时非常有用。
// www.javascriptcn.com code example
class Parent {
greet() {
return 'Hello from Parent';
}
}
class Child extends Parent {
greet() {
return super.greet() + ' and Hello from Child';
}
}
const child = new Child();
console.log(child.greet()); // 输出: Hello from Parent and Hello from Child在这个例子中,Child 类覆盖了 Parent 类的 greet 方法,但在 Child 的 greet 方法中,通过 super.greet() 调用了父类的 greet 方法,并在此基础上添加了额外的内容。
3. 访问父类的属性
super 也可以用于访问父类的属性。
// www.javascriptcn.com code example
class Parent {
constructor() {
this.name = 'Parent';
}
}
class Child extends Parent {
getName() {
return super.name; // 访问父类的属性
}
}
const child = new Child();
console.log(child.getName()); // 输出: Parent在这个例子中,Child 类通过 super.name 访问了父类 Parent 的 name 属性。
4. 注意事项
super()必须在子类构造函数的最开始调用,否则会抛出错误。- 在静态方法中,
super用于调用父类的静态方法。 super只能在子类的构造函数或方法中使用,不能在普通函数中使用。
通过 super 关键字,JavaScript 实现了类的继承和方法的重写,使得代码更加灵活和可维护。