子类构造函数中必须先调用 super() 才能访问 this,否则报错;super() 负责初始化 this 的内部状态和原型链,之后 this 才可用。

在 JavaScript 类继承中,this 的正确传递和使用关键在于:**子类构造函数中必须先调用 super(),才能访问 this;且 super() 必须在使用 this 前执行**。这是语法强制要求,否则会报错 ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor。
为什么必须先调用 super()?
ES6 类的子类实例在创建时,其内部属性(如 [[Prototype]])尚未初始化,this 指向一个“未初始化状态”的对象。只有 super() 执行后,父类构造函数才会为该对象设置原型链、初始化基础属性,this 才真正可用。
这和 ES5 构造函数中手动绑定 this 或用 Object.setPrototypeOf(this, SubClass.prototype) 的逻辑本质一致,只是语法上被强制规范了。
如何安全地在子类中使用 this?
-
构造函数中:所有对
this的赋值或方法调用,必须写在super()之后 -
普通方法中:
this可直接使用,无需额外操作(因为实例已完整创建) -
静态方法中:
this指向当前类本身(不是实例),与继承无关,不涉及super() -
箭头函数中:若定义在实例上(如类字段),
this继承外层作用域(通常是实例);若定义在方法内,则按普通函数规则绑定
常见错误与修正示例
❌ 错误写法(this 在 super 前使用):
class Parent {
constructor(name) {
this.name = name;
}
}
class Child extends Parent {
constructor(name, age) {
console.log(this); // ❌ 报错!
super(name);
this.age = age;
}
}
✅ 正确写法:
class Child extends Parent {
constructor(name, age) {
super(name); // ✅ 必须第一句
this.age = age; // ✅ 此后 this 才可用
console.log(this); // ✅ 安全
}
}
⚠️ 注意:super() 不仅是调用父构造函数,它还负责初始化 this 的内部状态。即使父类构造函数为空,也必须显式调用 super()。
在方法中调用父类同名方法时的 this 指向
当在子类方法中用 super.method() 调用父类方法时,该方法内部的 this 仍指向当前子类实例(不是父类实例)。这是 JavaScript 继承设计的核心特性——方法调用保持原始调用者上下文。
例如:
class Parent {
getName() {
return this.name;
}
}
class Child extends Parent {
constructor(name) {
super();
this.name = 'child: ' + name;
}
getInfo() {
return super.getName(); // this 指向 Child 实例,返回 'child: xxx'
}
}
不复杂但容易忽略
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











