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

在 JavaScript 的 class 语法中,super 关键字扮演着非常关键的角色,尤其是在实现继承时。它让我们可以在子类中调用父类的构造函数和方法,是实现面向对象编程中“继承”机制的重要工具。
super 的基本作用
super 可以在子类中引用父类,具体用途包括:
调用父类的构造函数(使用 super()) 调用父类的普通方法(使用 super.methodName()) 调用父类的 getter/setter
在子类的 constructor 中,必须先调用 super() 才能使用 this,否则会报错。
在 constructor 中使用 super()
当定义一个继承自另一个类的子类时,子类的构造函数必须先调用 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
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关键字详解的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1539026.html
微信扫一扫
支付宝扫一扫