JS class继承_Super关键字详解
发布时间:2025-11-15 15:18
发布者:网络
浏览次数:super关键字用于子类调用父类的构造函数和方法。1. 子类constructor中必须先调用super()才能使用this;2. 可通过super.method()调用父类实例方法;3. 在静态方法中可用super调用父类静态方法,实现逻辑复用与继承。

在 J*aScript 的 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 还可以用来调用父类的其他方法。这在需要扩展或覆盖父类行为时特别有用。
Visla
AI视频生成器,快速轻松地将您的想法转化为视觉上令人惊叹的视频。
100
查看详情
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关键字详解的详细内容,更多请关注其它相关文章!
# javascript
# java
# js
# 工具
# 面向对象编程
# speak
# 子类
# 面向对象
# 必须先
# 报错
# 有什么区别
# 自己的
# 类中
# 复用
# 您的
# 如何防止
# 网站排名推广优化怎么做
# 中山电器网站建设
# 怎么营销江湖菜品推广页
# 下拉关键词排名都选mars
# 宝鸡网站建设大全
# 金华网站建设报价模板
# 做小网站推广哪个好
# seo pdf教程
# 泰安网站建设制作开发
# 今科网站建设公司




