1

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'
kevzettler
  • 4,783
  • 15
  • 58
  • 103
  • 2
    Classes are mostly just syntactic sugar for functions and prototypes. If you want to make changes dynamically, do it by manipulating the prototypes. – Barmar Jun 12 '20 at 05:10
  • Here's a pretty similar question: https://stackoverflow.com/questions/42599560/javascript-class-extend-on-condition/42599645#42599645 – Duc Nguyen Jun 12 '20 at 07:56

1 Answers1

0

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;
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • no, unfortunately this is confusing, I essentially want the `super` of `InputClass` to propagate to `InnerClass` – kevzettler Jun 12 '20 at 14:19
  • @kevzettler That's not really possible, there is no `super()` in `InputClass` so it won't propagate. – Bergi Jun 12 '20 at 14:31
  • you're telling us even with extreme prototype manipulation that "its not really possible?" Just want to make sure before I stop pursuing – kevzettler Jun 13 '20 at 08:30
  • 1
    @kevzettler Yes. it is not possible if the "decorated" class did not already inherit from something (i.e. used `extends`). Your only choice is to create a new class then to overwrite the "decorated" class. – Bergi Jun 13 '20 at 09:54