I'm trying to construct an instance of a class using the output from a MongoDB database. My problems lies in that my class has nested classes, which I would also like to instantiate. Using Object.assign() seems to only create a top level object, while the inner properties are still 'object', so I don't have access to their methods. For example
let obj = {address: { street: '1234 Rainbow Road' }};
class Person {
constructor(obj) {
Object.assign(this, obj);
}
}
class Address {
constructor(addr) {
this.address = addr;
}
printAddress() {
console.log(this.address);
}
}
let p = new Person(obj);
p.address.printAddress() // fails, no function printAddress
compared to...
class Person {
constructor(obj) {
this.address = new Address(obj.address);
}
}
class Address {
constructor(addr) {
this.address = addr;
}
printAddress() {
console.log(this.address);
}
}
let p = new Person(obj);
p.address.printAddress() // works
This is just an example, my class is quite a bit larger, is there a way to shorthand instantiate all inner classes as well? Or would I have to decompose it like I did in the second code snippet? Thanks!