15

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

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

this = {...this, ...values}
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424

2 Answers2

32

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
1

Seeing your use of the spread operator, it looks like you're using a Stage 3 proposal for ECMAScript.

https://github.com/tc39/proposal-object-rest-spread

Try the Object.assign method:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Object.assign(target, ...sources);

Alex
  • 320
  • 4
  • 9
Ad.Infinitum
  • 316
  • 1
  • 7