vendredi 6 mars 2020

How can one combine classes in nodejs?

i am having difficulty figuring out how to best combine classes (i.e. create an aggregate class of sorts) in a nodejs app. currently, the design pattern i'm using is ad hoc and is isomorphic to the snippet below:

// some arbitrary base class
class Person {
  constructor(name, rank) {
    this.name = name;
    this.rank = rank;
  }

  sit() {
    return `${this.name} is sitting!`;
  }

  stand() {
    return `${this.name} is standing!`;
  }
}

// some more elaborate class which extends base class
class Developer extends Person {
  constructor(name, rank) {
    super(name, rank);
  }

  writeCode() {
    return `${this.name}:${this.rank} is writing code!`;
  }

  eatSnacks() {
    return `${this.name}:${this.rank} is eating snacks!`;
  }
}

var candidates = [
  { name: 'adam', rank: 9 },
  { name: 'sarah', rank: 2 },
  { name: 'reed', rank: 4 },
  { name: 'sasha', rank: 3 }
];

// composition of combined/aggregate class
var team = new Person('leader', 1);
candidates.forEach((p) => {
  team[p.name] = new Developer(p.name, p.rank);
});

is there anything inherently wrong with this approach? is there a well-adopted preferred approach? any glaring caveats with my approach that i am failing to see?

any input or help would be very much appreciated! thanks in advance!

Aucun commentaire:

Enregistrer un commentaire