mardi 26 novembre 2019

Why isn't the "has-a" pattern more used in Javascript? [on hold]

I am a big fan of composition over inheritance in JS, so I use the "has-a" pattern a lot. Sometimes using this pattern forces me to pass the parent to the child in case it needs to access some parent's method.

The parent class:

import { ChildClass } from "./child.js";

class ParentClass {
  constructor() {
    this.someValue = 3;
    this.child = new ChildClass(this);
  }

  someFn() {
    console.log("Value from parent: ", this.someValue);
  }

  test() {
    this.child.printParentValue();
    this.child.callParentFn();
  }
}
const parent = new Parent();
parent.test(); // works fine, prints both "Value from parent" and "Value from child"

And the child class:

export class ChildClass {
  constructor(parent) {
    this.parent = parent;
  }

  printParentValue() {
    console.log("Value from child: ", this.parent.someValue);
  }

  callParentFn() {
    this.parent.someFn();
  }
}

However, I haven't seen this pattern used in another codebase yet, nor the this.parent = parent thing.

Why isn't the "has-a" pattern more used in JS? Am I programming "against the language" here? Is there some other, more idiomatic pattern allowed by the language that I might be missing?

Aucun commentaire:

Enregistrer un commentaire