ES6 标准引入了类 class 的概念,常常被用于创建一个对象。类中有个特殊的方法 constructor ,它的返回值有一些让人迷惑的地方。

先简单梳理一下使用关键词 new 创建一个对象时发生了什么:

  1. 创建一个空对象
  2. 将 this 指向该对象,然后执行 constructor 函数中的代码,将一些数据通过 this 赋值给对象
  3. 返回 this

默认情况下, constructor 方法返回 this ,所以说下面某行代码 return this 是没必要写上去的。

class MyClass {
  constructor() {
    this.val = 10;
    return this;
  }
}
new MyClass(); // {val: 10}

但是,如果手动地在 constructor 方法中返回一个合理的值,比如一个对象 {name:"js"} ,那么 constructor 方法将返回 {name:"js"} :

class MyClass {
  constructor() {
    this.val = 10;
    return { name: "js" };
  }
}
new MyClass(); // {name: "js"}

如果手动地返回一个看似不合理的值,例如 2,那么 constructor 方法仍然返回 this:

class MyClass {
  constructor() {
    this.val = 10;
    return 2;
  }
}
new MyClass(); // {val: 10}
  • 合理的值: null 、数组、对象(引用类型)
  • 不合理的值:字符串、数字、 undefined (基本类型)