How to dynamically extend a class ref in javascript

247 Views Asked by At

I'd like to pass a class ref definition to a function. The function should then make the passed class ref extend another class. Heres an example. I would expect to see console.log output "Root constructor" but it does not because InputClass gets overriden with the extends line.

class Root {
  constructor(){
    console.log('Root constructor');
  }
}

function decorateClass(InputClass){
  class InnerClass {
    constructor(){

    }
  }

  // should extend InputClass but not override
  return class InputClass extends InnerClass{}
}

var ExtendedClass = decorateClass(Root);
var ec = new ExtendedClass();
// Should log 'Root constructor'
1

There are 1 best solutions below

4
On

Your code is extending the InnerClass, not the InputClass that you are passing to the function. The function argument is completely ignored.

I think you're looking for

function decorateClass(InputClass){
  class InnerClass extends InputClass {
//                 ^^^^^^^^^^^^^^^^^^
    constructor(){
      super();
    }
  }

  return InnerClass;
}