类构造函数中的ES6解构

时间:2015-09-05 12:25:53

标签: javascript ecmascript-6 destructuring

这可能听起来很荒谬,但请耐心等待。我想知道在语言层面是否支持将对象解构为构造函数中的类属性,例如

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

1 个答案:

答案 0 :(得分:29)

您无法在语言的任何位置分配this

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

constructor(human) {
  Object.assign(this, human);
}