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.
You can't update
thisby spreading and then assigning the result.You can use
Object.assign()to copy properties from theobjtothis:You can use destructuring to assign known properties to
this: