Skip to content

构造函数 / Constructor

constructor 是类 (class) 的一个特殊方法,如果在一个类中没有显示地声明构造函数,那么这个类会使用默认构造函数。

默认的 constructor

由其他类派生而来的类,或者说继承了其他类的类称之为派生类。

  1. 非派生类的默认构造函数 constructor(){}

  2. 派生类的默认构造函数 constructor(...args){super(...args)}

Super

子类构造函数中,需要先通过 super 关键字调用父类构造函数,才能使用 this 对象进行后续的操作,否则会出现引用错误。

javascript
class Animal {
  constructor() {
    this.hp = 100
  }
}
class Cat extends Animal {
  constructor() {
    // 注释掉 super() 会报错
    // ReferenceError: Must call super constructor in derived class 
    // before accessing 'this'
    // or returning from derived constructor
    super()
    // 派生类需要先调用 super 方法,才能访问 this 对象
    this.name = 'w'
  }
}