I am trying to implement named constructor usage in ES6. The reason for this is that I thought it would be more pleasing to avoid the constructor invocation with new keyword and instead use a simple method of the class to make use of other methods. I thought of using a static function for this as a Proxy for the constructor.

I tried the following:

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

But this won't work as simple object input gives:

Person {name: undefined, age: undefined}

Any help would be appreciated.

Update: Thanks, the answer by @appleapple helped a lot. I didn't notice the fact that I was passing a single argument. For those who are wondering how this could be done for n-Ary constructor method(of course using an object is neat, but still), here is an example:

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

2 Answers

3
apple apple On Best Solutions

not that complex, object is a single argument, so just pass it around.

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
apple apple On

reply to your update, actually you can forward the arguments (and I think the constructor looks better in this case)

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


or you can also take rest parameter in constructor (I don't like this, though)

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