此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

构造函数

基线
广泛可用

自 2016年3月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

constructor 是一种用于创建和初始化 class 对象实例的特殊方法。

备注:本页介绍 constructor 语法。关于所有对象的 constructor 属性,请参见 Object.prototype.constructor

尝试一下

class Polygon {
  constructor() {
    this.name = "Polygon";
  }
}

const poly1 = new Polygon();

console.log(poly1.name);
// Expected output: "Polygon"

语法

js
constructor() { /* … */ }
constructor(argument0) { /* … */ }
constructor(argument0, argument1) { /* … */ }
constructor(argument0, argument1, /* …, */ argumentN) { /* … */ }

还有一些额外的语法限制:

  • 名为 constructor 的类方法不能是 gettersetterasyncgenerator
  • 一个类不能有一个以上的 constructor 方法。

描述

通过构造函数,你可以在调用实例化对象的其他方法之前,提供必须完成的自定义初始化。

js
class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`你好,我的名字是 ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // 你好,我的名字是 Otto

如果不指定构造函数,则使用默认的构造函数。如果你的类是基类,默认构造函数会是空的:

js
constructor() {}

如果你的类是派生类,默认构造函数会调用父构造函数,并传递所提供的任何参数:

js
constructor(...args) {
  super(...args);
}

备注:像上面这样的显式构造函数与默认构造函数的区别在于,后者实际上并不通过参数展开来调用数组迭代器

这样代码才能正常工作:

js
class ValidationError extends Error {
  printCustomerMessage() {
    return `验证失败 :-((详细信息:${this.message})`;
  }
}

try {
  throw new ValidationError("非有效电话号码");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.name); // 这是 Error,而不是 ValidationError!
    console.log(error.printCustomerMessage());
  } else {
    console.log("未知错误", error);
    throw error;
  }
}

ValidationError 类不需要显式构造函数,因为它不需要进行任何自定义初始化。默认构造函数会根据给定的参数初始化父类 Error

但是,如果你提供了自己的构造函数,而你的类派生自某个父类,那么你必须使用 super() 显式地调用父类的构造函数。例如:

js
class ValidationError extends Error {
  constructor(message) {
    super(message); // 调用父类构造函数
    this.name = "ValidationError";
    this.code = "42";
  }

  printCustomerMessage() {
    return `发生未知错误 :-((详细信息:${this.message},错误代码:${this.code})`;
  }
}

try {
  throw new ValidationError("非有效手机号码");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.name); // 现在这是 ValidationError!
    console.log(error.printCustomerMessage());
  } else {
    console.log("未知错误", error);
    throw error;
  }
}

在类中使用 new,需要经过以下步骤:

  1. (如果是派生类)super() 调用之前的 constructor 主体。这部分不应访问 this,因为它尚未初始化。
  2. (如果是派生类)执行