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

问题描述 投票:1回答:2

我试图在ES6中实现命名构造函数用法。这样做的原因是我认为使用new关键字避免构造函数调用会更加愉快,而是使用类的简单方法来使用其他方法。我想使用静态函数作为构造函数的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();
javascript ecmascript-6 es6-class
2个回答
3
投票

不是那么复杂,对象只是一个参数,所以只需传递它。

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();

0
投票

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

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();
© www.soinside.com 2019 - 2024. All rights reserved.