0

I am new to Javascript ES6 class, i want to create object of multiple class at one time. does it is possible. below is my example

This file is in A.js

module.exports= class A{
 constructor(url){
    this.url = url;

  }
}

This file is in B.js

module.exports= class B{
 constructor(url){
    this.url = url;

  }
}

need to create instance of class A and class B at same time calling from different file ex: DE.js and return that instance

1 Answers1

1

Javascript has single inheritance, that means that every instance only has one prototype, so this:

instance -> A
          -> B

Is not possible. However we could create a copy of B, lets call it _B that inherits A, so we can create elements from that class that inherit both A and B:

instance -> _B -> A

We could create that class _B like this:

const Compose = (A, B) => {
  class _B extends A { // extend A
     constructor(...args) {
        super(...args); // construct A
        Object.assign(this, new B(...args)); // construct B
     }
   }

   // Copy B into _B
  Object.getOwnPropertyNames(B.prototype)
    .forEach(key => _B.prototype[key] = B.prototype[key]);

   return _B;
};

So we can just get our new class like this:

const AandB = Compose(A, B);
const instance = new AandB("http://example.com");
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151