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!
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.