Class 构造函数中的 ES6 解构
ES6 Destructuring in Class constructor
这听起来可能很荒谬,但请耐心等待。我想知道在语言级别是否支持将对象解构为构造函数中的 class 属性,例如
class Human {
// normally
constructor({ firstname, lastname }) {
this.firstname = firstname;
this.lastname = lastname;
this.fullname = `${this.firstname} ${this.lastname}`;
}
// is this possible?
// it doesn't have to be an assignment for `this`, just something
// to assign a lot of properties in one statement
constructor(human) {
this = { firstname, lastname };
this.fullname = `${this.firstname} ${this.lastname}`;
}
}
您不能在该语言的任何地方分配给 this
。
一个选项是合并到 this
或其他对象:
constructor(human) {
Object.assign(this, human);
}
这听起来可能很荒谬,但请耐心等待。我想知道在语言级别是否支持将对象解构为构造函数中的 class 属性,例如
class Human {
// normally
constructor({ firstname, lastname }) {
this.firstname = firstname;
this.lastname = lastname;
this.fullname = `${this.firstname} ${this.lastname}`;
}
// is this possible?
// it doesn't have to be an assignment for `this`, just something
// to assign a lot of properties in one statement
constructor(human) {
this = { firstname, lastname };
this.fullname = `${this.firstname} ${this.lastname}`;
}
}
您不能在该语言的任何地方分配给 this
。
一个选项是合并到 this
或其他对象:
constructor(human) {
Object.assign(this, human);
}