Reputation: 668
I want to transfer object's properties to a class' variables. For example:
const obj = {
a: 1,
b: 'hey',
}
class TestClass {
constructor(parentObject) {
// I need: this = parentObject, this.a must refers to parentObject.a, this.b = parentObject.b ...
...
}
}
const aClassObj = new TestClass(obj);
console.log(aClassObj.a); // should return 1
I don't want to make them equal in every line for example:
this.a = parentObject.a
this.b = parentObject.b
Whatever in parentObject
must be in this
.
Thanks!
Upvotes: 2
Views: 1014
Reputation: 12039
You can merge the object with the this
reference using Object.assign()
const obj = {a: 1,b: 'hey'}
class TestClass {
constructor(parentObject) {
Object.assign(this, obj)
}
}
const aClassObj = new TestClass(obj);
console.log(aClassObj.a);
Upvotes: 4