Can't assign this in constructor

ThomasReggi picture ThomasReggi · Apr 27, 2016 · Viewed 8.4k times · Source

I'm trying to merge the props from values into this.

The following throws an error. How can I do this?

this = {...this, ...values}

Answer

Роман Парадеев picture Роман Парадеев · Apr 27, 2016

You could extend this with Object.assign method:

class Foo {
  constructor (props) {
    Object.assign(this, props);
  }
}

const foo = new Foo({ a: 1 });
console.log(foo.a); // 1