我正在尝试在 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();
最佳答案
没那么复杂,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();
关于javascript - 如何在 ES6 中实现命名构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55841574/