0

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!

errorline1
  • 350
  • 1
  • 6
  • 18
  • related: [Casting plain objects to function instances (“classes”) in javascript](http://stackoverflow.com/q/11810028/1048572) – Bergi May 18 '16 at 22:46
  • I guess your `Address` class should have a `street` field not an `address` one? – Bergi May 18 '16 at 22:47

2 Answers2

1

You can call new Address in the argument list of new Person

let p = new Person(new Address({street: '1234 Rainbow Road'}));
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

The second version is good enough as design choice for a single property.

It doesn't look like the case for full-fledged DI container, but if the number of properties is big enough, some kind of class map may help to eliminate boilerplate code.

class Person {
  constructor(obj, classMap) {
    for (let prop of Object.keys(classMap)) {
      this[prop] = new classMap[prop](obj[prop]);
    }
  }
}

let p = new Person(obj, { address: Address });
Estus Flask
  • 206,104
  • 70
  • 425
  • 565