Justin Fagnani describes a very clean (imho) way to combine several classes into one, using the fact that in ES2015 classes can be created using class expressions.
Expressions against ads
Essentially, just like you can create a function with an expression:
function myFunction() {}
you can do the same with classes:
class MyClass {}
The expression is evaluated at runtime when the code is executed, while the declaration is executed in advance.
Using class expressions to create mixins
You can use this to create a function that dynamically creates a class only when the function is called:
function createClassExtending(superclass) { return class AwesomeClass extends superclass {
The cool thing about this is that you can define the whole class in advance and decide which class it should extend by the time the function is called:
class A {} class B {} var ExtendingA = createClassExtending(A) var ExtendingB = createClassExtending(B)
If you want to mix multiple classes together because ES6 classes support only one inheritance, you need to create a class chain that contains all the classes you want to mix together. Suppose you want to create a class C that extends both A and B, you can do this:
class A {} class B extends A {} class C extends B {}
The problem is that it is very static. If you later decide that you want to create a class D that extends B but not A, then you have a problem.
But with some tricky tricks using the fact that classes can be expressions, you can solve this problem by creating A and B not directly as classes, but as class factories (using the arrow functions for brevity):
class Base {}
Notice how we decide at the last moment which classes to include in the hierarchy.
Help us build the future!
Of course, if you look like me, it will inspire you to create the ultimate Javascript multiple inheritance library. If you are ready, please help me do just that! Check out this project and help if you can!
mics (pronunciation: mix) is a library that makes Javascript multiple inheritance fast. Inspired by the excellent Javascript mixins blog post by Justin Fagnani, the microphones are trying to create a minimal library around the concept of using class expressions (factories) as mixins. mics extends the concepts presented in the blog post, making mixins first-class citizens that you can directly use to create objects and mix them with other mixins, not just classes.