如何在 ES6 中实现命名构造函数

How to implement a named constructor in ES6

我正在尝试在 ES6 中实现命名构造函数用法。这样做的原因是我认为避免使用 new 关键字调用构造函数会更令人愉快,而是使用 class 的简单方法来利用其他方法。我想为此使用静态函数作为构造函数的 Proxy

我尝试了以下方法:

class Person {
  constructor(...props) {
    let {name, age} = props;
    this.name = name;
    this.age = age;
  }
  static create(...props) {
    return new Person(props);
  }
  
  display() {
    console.log(this)
  }
}

Person.create({name: 'John', age: 28}).display(); //Simple object input

但这不会像简单的对象输入那样工作:

Person {name: undefined, age: undefined}

如有任何帮助,我们将不胜感激。

更新:谢谢,@appleapple 的回答帮了大忙。我没有注意到我传递了一个论点。对于那些想知道如何为 n-Ary 构造函数方法完成此操作的人(当然使用对象很整洁,但仍然如此),这里有一个例子:

class Person {
  constructor([name, age ]) {
    this.name = name;
    this.age = age;
  }
  static create(...props) {
    return new Person(props); //return new this(props); also works
  }
  
  display() {
    console.log(this)
  }
}

Person.create('John', 28).display();

没那么复杂,object 是一个单一的参数,所以只是传递它。

class Person {
  constructor(props) { // <-------
    let {name, age} = props;
    this.name = name;
    this.age = age;
  }
  static create(props) { // <-------
    return new Person(props); 
  }

  display() {
    console.log(this)
  }
}

Person.create({name: 'John', age: 28}).display();

回复你的更新,实际上你可以转发参数(我认为在这种情况下构造函数看起来更好)

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  static create(...props) {
    return new Person(...props); // <----------
  }
  
  display() {
    console.log(this)
  }
}

Person.create('John', 28).display();


或者你也可以在构造函数中使用 rest 参数(不过我不喜欢这样)

class Person {
  constructor(...props) {  // <----------
    let [name, age]=props
    this.name = name;
    this.age = age;
  }
  static create(...props) {
    return new Person(...props); // <----------
  }
  
  display() {
    console.log(this)
  }
}

Person.create('John', 28).display();