- http://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes/
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Mix-ins
A mixin is an abstract subclass; i.e. a subclass definition that may be applied to different superclasses to create a related family of modified classes.
Gilad Bracha and William Cook, Mixin-based Inheritance
- mixin definition: The definition of a class that may be applied to different superclasses.
The mixin definition is really a subclass factory, parameterized by the superclass, which produces mixin applications.
const RandomizeMixin = (Base) => class extends Base {
randomize() { ... }
}
- mixin application: The application of a mixin definition to a specific superclass, producing a new subclass.
A mixin application sits in the inheritance hierarchy between the subclass and superclass.
class Child extends RandomizeMixin(Parent) {
...
}
- subclass has a fixed superclass, while a mixin definition doesn't yet have a superclass
- Only the mixin applications have their own superclasses
- see subclass inheritance as a degenerate form of mixin inheritance where the superclass is known at class definition time, and there's only one application of it
class App extends Base with Mixin { ... }
// superclass of App = __Base with Mixin__ (mixin application)
// inheritance hierarchy: App --> Base with Mixin --> Base --> Object
- Subclass can override mixin methods
super
works- Composition: two mixins can define the same method, and as long as they call
super
, both of them will be invoked then applied