Skip to content

Instantly share code, notes, and snippets.

@royling
Last active April 21, 2017 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save royling/5c7ae66a80446f4bda4457363ee770bd to your computer and use it in GitHub Desktop.
Save royling/5c7ae66a80446f4bda4457363ee770bd to your computer and use it in GitHub Desktop.
Mixins vs. subclass in JavaScript

References

Mixin

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) {
  ...
}

Mixin vs. subclass

  • 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

Mixin in Dart

class App extends Base with Mixin { ... }
// superclass of App = __Base with Mixin__ (mixin application)
// inheritance hierarchy: App --> Base with Mixin --> Base --> Object

Benefits

  • 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment