mardi 14 septembre 2021

Composition Pattern in Javascript with Classes but without Mixins?

Is the following a valid strategy for implementing the composition pattern in Javascript? I want to use classes instead of constructor functions or plain objects, and I know that Mixins are not best practice. One concern is that in this approach, the methods added to Person objects are not attached to the prototype and therefore each require memory allocation. Thanks!

class Person {
  name;
  constructor(name) {
    this.name = name;
  }
}

function fly() {
  return {
    fly() {
      console.log(`${this.name} can fly!`);
    },
  };
}

function swim() {
  return {
    swim() {
      console.log(`${this.name} can swim!`);
    },
  };
}

function makeFlyingPerson(name) {
  return Object.assign(new Person(name), fly());
}

function makeSwimmingPerson(name) {
  return Object.assign(new Person(name), swim());
}

Aucun commentaire:

Enregistrer un commentaire