32

这可能听起来很荒谬,但请容忍我。我想知道语言级别是否支持将对象解构为构造函数中的类属性,例如

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}`;
    }
}
4

1 回答 1

54

您不能分配到this该语言中的任何位置。

一种选择是合并到this或其他对象:

constructor(human) {
  Object.assign(this, human);
}
于 2015-09-05T13:18:38.470 回答