Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 43

Crafting Functional Mixins

This lesson is built with resources from youtube.com, justinfagnani.com and 1 more site.

Hello! Let's dive into the next stage of our exploration of compositional patterns.

In our last lesson, we implemented simple mixins by merging properties with Object.assign. We saw it was a quick way to share behavior but came with significant drawbacks: name collisions, direct mutation of prototypes, and most critically, the breaking of the prototype chain, which renders super calls useless.

Today, we'll address those issues head-on. Our learning goal is to create functional mixins that can be applied to any class. This powerful pattern leverages ES6 class expressions to create true compositional inheritance, building clean, robust, and extensible prototype chains.

From Copy-Paste to Subclass Factories

The core issue with the Object.assign approach is that it copies properties rather than establishing a true inheritance link. This is a shallow, brittle form of composition. A better approach is to think of a mixin not as a bucket of properties to copy, but as an "abstract subclass"—a template for creating a subclass that can be applied to any superclass.

The article "'Real' Mixins with JavaScript Classes" by Justin Fagnani is a foundational text on this topic. It eloquently explains the pitfalls of the traditional approach and introduces the modern solution.

"Real" Mixins with JavaScript Classes

To start, let's solidify our understanding of why the Object.assign pattern is insufficient. Please read the section 'Traditional JavaScript Mixins' from Justin Fagnani's article.

Read the section titled 'Traditional JavaScript Mixins' and the subsection 'What's So Bad About That?'. Focus on the four key problems identified: modifying prototypes, non-functional super, incorrect precedence, and compromised composition.

As the article highlights, a true mixin shouldn't just be a property bag. It should be a link in the prototype chain. Let's see how to build that.


The Functional Mixin Pattern

The solution is both elegant and powerful, and it relies on two key features of ES6:

  1. The class keyword can be used in an expression, which evaluates to a new class each time.
  2. The extends clause can accept any expression that resolves to a constructor (a class).

Combining these, we can define a mixin as a function that takes a superclass as an argument and returns a new class that extends it. This function acts as a "subclass factory."

Let's read the section of the same article that introduces this pattern.

"Real" Mixins with JavaScript Classes

Now for the solution. This section introduces the core concept of functional mixins, or 'subclass factories'.

Read the section 'Better Mixins Through Class Expressions', stopping before 'Benefits of Mixins as Subclass Factories'. Pay close attention to the syntax let MyMixin = (superclass) => class extends superclass { ... } and how multiple mixins are composed through function nesting.

The core pattern is this:

const MyMixin = (superclass) => class extends superclass {
  // Add new methods or override existing ones
  mixinMethod() {
    console.log("Method from the mixin!");
  }
};

Here, MyMixin is not an object, but a function. When we call it with a base class, it returns a new class definition that inherits from the one we passed in.

To apply it, you use it directly in the extends clause:

class BaseClass {
  baseMethod() {
    console.log("Method from the base class.");
  }
}

// Apply the mixin to BaseClass
class MyExtendedClass extends MyMixin(BaseClass) {
  // This class now has mixinMethod() and baseMethod()
}

const instance = new MyExtendedClass();
instance.baseMethod();   // "Method from the base class."
instance.mixinMethod();  // "Method from the mixin!"

This pattern is also explained very concisely in the "ExploringJS" book.

15. Classes

For a supplementary perspective, the 'ExploringJS' book offers a clear, practical example of this same pattern.

Read section '15.4 Simple mixins'. Note how the Storage and Validation mixins are defined as functions that accept a superclass (Sup) and how they are chained together to create the Employee class.


The Power of a Real Prototype Chain

Because this pattern constructs a proper prototype chain, it solves all the problems of the Object.assign method.

JavaScript Mixin and Prototype Chain Diagram
This diagram illustrates the kind of prototype chain that functional mixins create. Each mixin application adds a new layer to the chain, allowing methods to delegate upwards via `super` just as with standard inheritance.

The most significant benefit is that super works exactly as you'd expect. A method in a subclass can call super to access the method in the mixin, which in turn can call super to access the method in the base class.

This is best understood with an example.

"Real" Mixins with JavaScript Classes

Let's explore the benefits of this pattern, especially how it enables super to work across the entire inheritance chain.

Read the subsection 'Benefits of Mixins as Subclass Factories'. The code example demonstrating the super.foo() chain is crucial. Trace the call stack from new C().foo() to see how it flows through the subclass, both mixins, and the original superclass S.

As you saw, applying multiple mixins is as simple as nesting the function calls. The order is inside-out:

// The final class extends the result of Mixin1 applied to (Mixin2 applied to BaseClass)
class MyFinalClass extends Mixin1(Mixin2(BaseClass)) { ... }

The resulting prototype chain will be: MyFinalClass.prototype -> Mixin1 -> Mixin2 -> BaseClass.prototype.


A Practical Demonstration

Let's watch a video that implements a functional mixin. The video uses TypeScript, but the underlying JavaScript pattern is identical. Your experience with typed languages will make it easy to see past the type annotations and focus on the core logic.

No BS TS #17 - Mixins in Typescript

This video from Jack Herrington provides a practical walk-through of creating and applying a functional mixin.

Please watch the following segments. Focus on the JavaScript structure and ignore the TypeScript type annotations (e.g., : T, <T>). 01:23 - 03:17: This section shows the basic premise: a function that returns a class. 05:40 - 06:15: This is the key part where he creates the dumpable functional mixin. Notice the (base) => class extends base structure. 07:43 - 08:38: Here he applies the mixin (dumpable(StringDatabase)) and uses the new functionality. The sections discussing advanced generics (around 06:15 and 08:38) are specific to ensuring type safety in TypeScript. In plain JavaScript, we rely on documentation and runtime checks to ensure a mixin is applied to a compatible class.

The video demonstrates the pattern perfectly: a dumpable function takes a base class and returns a new class that extends it, adding a dump method. This creates a reusable piece of functionality that can be applied to any class that has the methods the mixin depends on.

Test your understanding!

You are building a logging system. You have a basic Logger class that just prints messages.

class Logger {
  log(message) {
    console.log(message);
  }
}

Create two functional mixins:

  1. Timestamp: This mixin should prepend the current ISO date string to the message before calling the parent's log method.
  2. WithLoggerName: This mixin takes a name in its constructor. It should prepend [name] to the message before calling its parent's log method.

Finally, create a SpecialLogger class that uses both mixins on top of the Logger base class. The final output should look something like: 2023-10-27T10:00:00.000Z [MyLogger] This is a test.

Show answer

First, let's define the two functional mixins.

// 1. Timestamp Mixin
const Timestamp = (superclass) => class extends superclass {
  log(message) {
    const timestampedMessage = `${new Date().toISOString()} ${message}`;
    // Use super to call the next method in the prototype chain
    super.log(timestampedMessage);
  }
};

// 2. WithLoggerName Mixin
const WithLoggerName = (superclass) => class extends superclass {
  constructor(name, ...args) {
    // Pass any remaining arguments up the chain
    super(...args);
    this.name = name;
  }

  log(message) {
    const namedMessage = `[${this.name}] ${message}`;
    // Use super to call the next method in the chain
    super.log(namedMessage);
  }
};

Note how WithLoggerName has its own constructor to capture the name, and it correctly calls super() to ensure the rest of the chain is constructed properly.

Now, let's compose them to create the SpecialLogger. The order matters! We want the name to be added after the timestamp for the desired output format, so WithLoggerName should be the outer mixin.

// Base class
class Logger {
  log(message) {
    console.log(message);
  }
}

// Chain the mixins: WithLoggerName(Timestamp(Logger))
class SpecialLogger extends WithLoggerName(Timestamp(Logger)) {
  constructor(name) {
    // The constructor argument 'name' is for WithLoggerName
    super(name);
  }
}

// --- Verification ---
const logger = new SpecialLogger("MyLogger");
logger.log("This is a test.");

// Expected Output (timestamp will vary):
// 2023-10-27T10:00:00.000Z [MyLogger] This is a test. 

The call chain for logger.log(...) is:

  1. Timestamp.log is called. It prepends the date.
  2. It calls super.log(), which resolves to WithLoggerName.log.
  3. WithLoggerName.log prepends the name.
  4. It calls super.log(), which resolves to the base Logger.log.
  5. Logger.log finally prints the fully assembled message to the console.

Conclusion

Today we've made a significant leap from simple property copying to a robust, inheritance-based composition pattern. Functional mixins provide a clean and powerful way to reuse code across different class hierarchies without the limitations of single inheritance.

Key Takeaways:

  • A functional mixin is a function that accepts a superclass and returns a new class that extends it.
  • This pattern creates a true prototype chain, which solves the problems of Object.assign-based mixins.
  • The extends clause in JavaScript is dynamic and can accept an expression, which is the language feature that makes this pattern possible.
  • super calls work correctly, allowing methods in the chain to delegate to their parents, enabling powerful, layered functionality.
  • Multiple mixins can be composed by nesting the function calls, e.g., Mixin1(Mixin2(BaseClass)).

Next Up

While nesting mixin functions is powerful, the syntax extends Mixin1(Mixin2(Mixin3(BaseClass))) can become unwieldy and hard to read. To improve this, we can build a small helper utility to provide a more declarative and robust syntax. In the next lesson, we will implement the mixin pattern with subclass factories for more robust composition, creating a cleaner API for applying our functional mixins.