super关键字用于子类调用父类的构造函数和方法。1. 子类constructor中必须先调用super()才能使用this;2. 可通过super.method()调用父类实例方法;3. 在静态方法中可用super调用父类静态方法,实现逻辑复用与继承。

在 JavaScript 的 class 语法中,super 关键字扮演着非常关键的角色,尤其是在实现继承时。它让我们可以在子类中调用父类的构造函数和方法,是实现面向对象编程中“继承”机制的重要工具。
super 可以在子类中引用父类,具体用途包括:
在子类的 constructor 中,必须先调用 super() 才能使用 this,否则会报错。
当定义一个继承自另一个类的子类时,子类的构造函数必须先调用 super(),否则无法正确初始化 this。
// 错误示例:未调用 super() class Parent { constructor(name) { this.name = name; } } class Child extends Parent { constructor(name, age) { // 没有调用 super(),会报错 this.age = age; // ReferenceError } } // 正确示例:先调用 super() class Child extends Parent { constructor(name, age) { super(name); // 调用父类构造函数 this.age = age; // 此时可以安全使用 this } } const c = new Child("Alice", 12); console.log(c.name, c.age); // Alice 12除了构造函数,super 还可以用来调用父类的其他方法。这在需要扩展或覆盖父类行为时特别有用。
class Animal { speak() { console.log("Animal makes a sound"); } } class Dog extends Animal { speak() { super.speak(); // 先调用父类的 speak() console.log("Dog barks"); // 再添加自己的逻辑 } } const dog = new Dog(); dog.speak(); // 输出: // Animal makes a sound // Dog barks这样既能保留父类的功能,又能在此基础上增强。
super 也可以在静态方法中使用,用于调用父类的静态方法。
class Parent { static info() { console.log("I'm the parent"); } } class Child extends Parent { static info() { super.info(); // 调用父类静态方法 console.log("I'm the child"); } } Child.info(); // 输出: // I'm the parent // I'm the child基本上就这些。super 是 class 继承的核心,理解它如何工作,对写出清晰、可维护的继承结构至关重要。关键是记住:子类 constructor 中必须调用 super(),且要在使用 this 之前。其他时候,super 可以帮助你复用父类逻辑,避免重复代码。
以上就是JS class继承_Super关键字详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号