在 javascript 中,super 关键字用于访问和调用对象原型链上的函数。它主要有两种用法:在类的方法中调用父类的构造函数或方法,以及在静态方法中引用父类的静态属性。

子类实例方法中如何调用父类构造函数和方法
在子类的 constructor 中,必须在使用 this 之前调用 super(),这会执行父类的构造函数并初始化继承的属性。在普通实例方法中,可以使用 super.methodName() 来调用父类同名方法,从而复用父类逻辑或扩展功能。

class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // 调用父类构造函数
this.breed = breed;
}
speak() {
super.speak(); // 调用父类方法
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Rex', 'German Shepherd');
dog.speak();
运行上述代码将输出:
Rex makes a noise. Rex barks.
静态方法中如何使用 super 引用父类静态成员
在类的静态方法(static method)中,super 指向的是父类本身,而不是实例。因此,可以使用 super.staticProperty 或 super.staticMethod() 来访问或调用父类的静态属性和方法。这在需要基于父类状态进行计算或扩展时非常有用。
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。

class Parent {
static value = 10;
static getValue() {
return Parent.value;
}
}
class Child extends Parent {
static value = 20;
static getValue() {
const parentValue = super.getValue(); // 调用父类静态方法
const childValue = Child.value; // 访问当前类静态属性
return { parentValue, childValue };
}
}
console.log(Child.getValue());
运行上述代码将输出:
{ parentValue: 10, childValue: 20 }
当父类方法不存在时 super 调用会怎样
如果在子类中通过 super.methodName() 调用的方法在父类原型链上不存在,JavaScript 引擎会抛出 TypeError。这是因为 super 解析的是原型链上的属性,如果找不到对应的方法,就无法执行调用。这种机制确保了类型安全,防止意外调用未定义的行为。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










