Mixins

This lesson teaches the concept of mixins in JavaScript, their syntax, and their implementation using an example.

What are Mixins?

For a class to call methods from another class it first needs to inherit those methods. The child class extends the parent’s class, inherits its methods, and then invokes them. However, there is a limiting factor: a class can only inherit from another class.

That brings us to the question:

Is there a class whose methods can be inherited by other classes without it having to be their parent class? This where mixins are implemented.

A mixin is a class that contains various methods implementing different functionalities. Other classes can then inherit those methods without having the mixin class be their parent class.

Note: A mixin class is not used alone. It only provides other classes with extra methods.

Syntax

Let’s take a look at the syntax to implement a mixin:

Get hands-on with 1200+ tech skills courses.