0

I couldn't find the solution to this issue. I am banging my head against a wall entire day.

Assume we have the following hierarchy of classes:

class A {
    async name() { ... } 
}
class B extends A {
    async age() { ... }
}
class C extends A {
    async group() { ... }
}

class D extends B {
    constructor() {
         super(...)
         this.C = new C(...);
    }
    async group() { return await this.C.group(); }
}

Because JavaScript doesn't support multiple inheritance, I have an issue. I would like to combine prototypes of objects in a way that I can invoke function group() without the need for writing repetitive code like above. It is absolute must to be able to invoke group() directly on the object D outside of the class, even though it is the an instance of class C.

How can I combine their prototypes? I've tried things like

class A {
  appendPrototype(obj) { 
    if (obj instanceof A)
        for (let k in obj.__proto__) {
            this.__proto__[k] = obj.__proto__[k];
        }
   }
} 
.
.
. // Same two classes, B and C
class D extends B {
    constructor(...) {
        super(...);
        const c = new C(...);
        this.appendPrototype(c);
    }
}

I can't invoke the function group() an instance of the class D. Why is that? How can I achieve it, without writing repetitive code like in the first example?

Shocky2
  • 444
  • 6
  • 22

1 Answers1

0

What you can do, it is to assign to the prototype of the class D, the method of the class C. In this way all the instances of D will have the group method which is the same method defined within the class C, and you can do the same for all the other child classes.

class A {
  async name() {
    console.log('A - name');
  } 
}
class B extends A {
  async age() {
    console.log('B - age');
  }
}
class C extends A {
  async group() {
    console.log('C - group');
  }
}

class D extends B {
  constructor() {
    super();
  }
}
D.prototype.group = C.prototype.group;

const d = new D(); 
d.group();

Anyway, in your case, I would go for composition (like you did with C within D) and then call the methods like:

d.c.group()

which allows you to avoid the appendPrototype logic.

quirimmo
  • 9,530
  • 2
  • 27
  • 43