super用于访问父类构造函数或方法:子类constructor中必须首行调用super()初始化this;普通方法中用super.方法名()调用父类方法,内部this仍指向子类实例。

在 JavaScript 的 class 语法中,super 用于访问和调用父类的构造函数或方法。它必须在子类的 constructor 中调用(且必须在使用 this 之前),否则会报错。
在子类 constructor 中调用父类构造函数
子类定义自己的 constructor 时,必须第一行调用 super(),把参数传给父类初始化逻辑:
class Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // ✅ 必须先调用,初始化 this.name
this.breed = breed; // ✅ 此后才能使用 this
}
}
const dog = new Dog('旺财', '金毛');
console.log(dog.name); // '旺财'
console.log(dog.breed); // '金毛'
在普通方法中调用父类同名方法
如果子类重写了父类的方法,又想复用父类逻辑,可在方法体内用 super.方法名() 调用:
你接手一个需求时,是不是经常这样:"改一个小字段 → 结果把不相关的代码也改了"、"需求说得很模糊 → 做着做着发现跑偏了"、"数据库加个字段 → 上线才发现漏了数据兼容"、"做了个新功能 → 一个月后自己都忘了当时怎么设计的"、"写到一半被中断 → 再回来不知道从哪继续";这个 Skill 就是专门解决这些问题的。 它会自动探测你的项目环境(JDK、Spring Boot、ORM、数据库、前端框架),记在
-
super在方法中指向父类的原型对象(Parent.prototype) - 不能直接写
super()(那是构造函数调用语法),要带方法名 - 可以传参、接收返回值,和普通方法调用一样
class Animal {
speak() {
return `${this.name} 发出声音`;
}
}
class Cat extends Animal {
speak() {
return super.speak() + ' —— 喵喵!'; // ✅ 复用父类逻辑再扩展
}
}
const cat = new Cat('咪咪');
console.log(cat.speak()); // '咪咪 发出声音 —— 喵喵!'
注意 this 和 super 的绑定时机
super 不是独立对象,它的行为依赖于当前函数的调用上下文:
- 在
constructor中,super()初始化this,并绑定到新实例 - 在普通方法中,
super.method()内部的this仍是当前子类实例(不是父类实例) - 不能在箭头函数或单独赋值的函数中用
super(会报ReferenceError)
常见错误示例
以下写法都会报错:
-
constructor() { console.log(this); super(); }→this在super()前不可用 -
constructor() { super(); return {}; }→ 子类构造函数若显式返回对象,必须是对象,但不能破坏原型链(一般不建议返回) -
const fn = () => super.say();→ 箭头函数里不能用super -
class B extends A { method() { super(); } }→super()只能在constructor中作为函数调用
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










