35

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}`;
    }
}
Lim H.
  • 9,870
  • 9
  • 48
  • 74
  • If you want `fullname` to retain changes in `firstname` and `lastname`, use a getter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get – Jan Sep 05 '15 at 18:07
  • @Jan right thanks. Sorry it was a bad example. I just want to demonstrate that after `firstname` and `lastname` there are more initialization if that makes sense. – Lim H. Sep 05 '15 at 18:13
  • `this` cannot be assigned to - in ES5 never, in ES6 the only thing that changes its "value" is `super()`. But to assign properties on it, see the duplicate. – Bergi Sep 05 '15 at 19:37

1 Answers1

58

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);
}
  • 3
    Cheers. I know we can't assign to this but was hoping for something similar. I was very keen on using destructuring because it has a clear schema, i.e. telling me which properties are being assigned. But anyway, thank you for the answer. – Lim H. Sep 05 '15 at 14:54
  • 6
    Or maybe you need this? constructor({ firstname, lastname }) { Object.assign(this, {firstname, lastename}); this.fullname = `${this.firstname} ${this.lastname}`; } – roeland Apr 13 '16 at 20:17
  • @r03 have u tried that solution ?it actually works ? – Felipe Quirós Mar 26 '17 at 16:22
  • Why wouldn't it work? –  Mar 26 '17 at 16:30
  • 8
    There's no *destructuring* in this answer.. – vsync Jul 11 '18 at 07:36
  • this remove intellisence in the VScode ide. – jon Sep 11 '20 at 15:56