constructor是类的强制入口,new实例时首先调用,决定this指向和初始状态;未显式声明时引擎自动注入空函数,显式声明则必须用this挂载属性,且子类constructor首行须调用super()。

constructor 不是“可选配置”,它是 class 的核心执行入口,new 一个实例时,它第一时间被调用,且直接决定 this 指向和初始状态。理解它,等于抓住了 ES6 类行为的开关。
constructor 是类的强制入口,不是可选项
即使你没写 constructor,JavaScript 也会自动补上一个空的 constructor() {}。但一旦你显式声明,就必须遵守规则:只能有一个,不能重名,否则语法报错。它不是普通方法,而是类初始化阶段唯一被自动触发的钩子。
- 不写 constructor → 引擎注入空函数,实例创建后 this 存在但无属性
- 写了 constructor → 必须用
this.xxx =显式挂载属性,否则该属性不会出现在实例上 - 不能在 class 大括号顶层直接写
this.name = 'xxx',那会报错——所有实例属性必须在 constructor 内赋值
constructor 中的 this 指向新实例,且不可替换(除非主动返回对象)
默认情况下,constructor 执行完自动返回 this,也就是刚创建的那个空白对象。但你可以手动 return 一个对象,这时 new 的结果就不再是当前类的实例:
-
return this→ 正常返回实例,instanceof MyClass为 true -
return { x: 1 }→ 返回全新对象,instanceof MyClass变成 false -
return null / undefined / 基本类型→ 仍返回 this,不影响 instanceof 判断
继承时 super() 不是“建议调用”,而是 this 初始化的前提
子类 constructor 第一行必须调用 super(),否则访问 this 会报错 “Must call super constructor in derived class before accessing ‘this’”。因为父类的 constructor 负责给 this 绑定原型链和基础属性,没它,子类的 this 就没准备好。
-
super()相当于执行父类 constructor,把父类逻辑跑一遍 -
super(a, b)可传参,参数会交给父类 constructor 处理 -
super()必须在使用this之前调用,顺序错误直接抛异常
constructor 和 class 本质:它仍是函数,只是写法更规范
class Person 本质上等价于 function Person,constructor 就是这个函数体本身。typeof Person === 'function',Person === Person.prototype.constructor 都为 true。所谓“语法糖”,是指它把原型链操作、this 绑定、new 约束这些隐性逻辑显性化、结构化了。
- class 不会被提升,而函数声明会被提升 —— 这是关键差异
- class 内部默认启用严格模式,没有 arguments / caller 等非严格特性
- class 定义的方法不可枚举(for...in 看不到),比传统 prototype 写法更干净


















