Dynamic super classes (extends) in ES6

tl;dr

Create a class factory which allows dynamic super classes to by applied to an es6 class (dynamic inheritance). This will be transparent to a consumer — meaning they will interact with it in the same way as the initial class.

Problem statement:

I was recently working on some code which extended an asynchronous module to add some additional functionality. The class initially looked like this:

However, testing a module like this is difficult for two reasons.

  1. The async nature of the behavior is challenging to test and mock
  2. The explicit super class Fetcher which is imported in the module is difficult to override without reaching down into the prototype and manually modifying methods during the test. Yuck!

Solution:

Wrap the extending (child) class declaration with a function, which accepts a parameter for its super class, and a default parameter value. Then the inner class can be declared using the SuperClass parameter. This will allow the child class to reference either its default parent, or the custom super class explicitly passed in.

The child class then extends or overwrites any methods from super that are required. Finally, a new’d up instance of the child class is returned with the remaining arguments passed to the class factory function.

For consistency of use, we can force the function to be called using new, making the abstraction completely transparent to any consumer.

Now we can call the extending class (with no SuperClass property) and it will have its default and expected behavior:

Or, with the SuperClass property to dynamically set its parent:

Working Example

 

See the Pen dynamic super class by Michael Jasper (@mdjasper) on CodePen.

Author: Michael Jasper

Michael is a Web Developer located in Northern Utah. When not programming, he enjoys spending time with his family, exploring the great-outdoors, and hit-and-miss cooking experiments.