这可能听起来很荒谬,但请耐心等待。我想知道在语言层面是否支持将对象解构为构造函数中的类属性,例如
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}`;
}
}
答案 0 :(得分:29)
您无法在语言的任何位置分配this
。
一种选择是合并到this
或其他对象:
constructor(human) {
Object.assign(this, human);
}