ES6 Destructuring in Class constructor

Lim H. picture Lim H. · Sep 5, 2015 · Viewed 16.3k times · Source

This may sound ridiculous but bear with me. I wonder if there is support on the language level to destructure object into class properties in constructor, e.g.

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

Answer

user663031 picture user663031 · Sep 5, 2015

You cannot assign to this anywhere in the language.

One option is to merge into this or other object:

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