Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't assign this in constructor [duplicate]

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

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

this = {...this, ...values}
like image 823
ThomasReggi Avatar asked Apr 27 '16 18:04

ThomasReggi


2 Answers

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
like image 147
Роман Парадеев Avatar answered Oct 19 '22 20:10

Роман Парадеев


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);

like image 39
Ad.Infinitum Avatar answered Oct 19 '22 21:10

Ad.Infinitum