1

I know we can do something like:

const a = { b: 1, c: 2 }

const A = { ...a };
// A { b: 1, c: 2 }

But how do we use this approach to pass data into this value?

For example we have a class A {} and want to dynamically set object property into this. The usual way would be using Object.defineProperties with maybe for...in loop:

const a = { b: 1, c: 2 }

class A {
  constructor(obj){
    for (const k in obj)
      Object.defineProperty(this, k, { value: obj[k] });
  }
}

new A(a);
// A { b: 1, c: 2 }

So I'm thinking, since we have the syntactic sugar now, how can we utilise it to the example above?

EDIT

I am talking about spread operator syntax ... here.

yqlim
  • 6,898
  • 3
  • 19
  • 43
  • you can't use `...` to put values in `this` because `this` is a reserved keyword, and you can't use reserved keywords as variable names – 0.sh Nov 17 '18 at 03:46
  • ...and you shouldn't really want to. `this` is an `A` instance. If you replace it, it won't be an instance of your class anymore, which defeats the purpose of making a class. – Mark Nov 17 '18 at 04:07
  • [`...` is not an operator!](https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/37152508#37152508) – Felix Kling Nov 17 '18 at 06:12
  • "*The usual way would be using Object.defineProperties*" - no, it would be a simple assignment, like `this[k] = obj[k];`. Why did you use `Object.defineProperty`? – Bergi Nov 17 '18 at 17:13

1 Answers1

5

You can't update this by spreading and then assigning the result.

You can use Object.assign() to copy properties from the obj to this:

class A {
  constructor(obj) {
    Object.assign(this, obj);
  }
}

const a = { b: 1, c: 2 }

console.log(new A(a));

You can use destructuring to assign known properties to this:

class A {
  constructor(obj) {
    ({ b: this.b, c: this.c } = obj);
  }
}

const a = { b: 1, c: 2 }

console.log(new A(a));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209