MediumObjects📖 Theory Question

What are mixins in JavaScript and why are they used?

💡

Hint

Copy methods from multiple sources into a class — avoids single-inheritance limits

Full Answer

A mixin is a pattern to copy methods from one object into another class or prototype, enabling code reuse without inheritance chains.

// Mixin objects (plain objects with methods)
const Serializable = {
  serialize() { return JSON.stringify(this); },
};

const Validatable = {
  validate() {
    return Object.values(this).every(v => v !== null && v !== undefined);
  }
};

class User {
  constructor(name, email) {
    this.name = name;
    this.email = email;
  }
}

// Apply mixins — copy methods onto the class prototype
Object.assign(User.prototype, Serializable, Validatable);

const u = new User('Alice', 'a@b.com');
u.serialize(); // '{"name":"Alice","email":"a@b.com"}'
u.validate();  // true

// More modern approach: mixin factory functions
const withLogging = (Base) => class extends Base {
  log(msg) { console.log(`[${this.constructor.name}] ${msg}`); }
};

class LoggableUser extends withLogging(User) {}

Mixins solve the diamond problem of multiple inheritance — compose behavior from multiple independent sources.

💡 React class component mixins were deprecated in favour of Hooks. Hooks are the modern mixin equivalent — reusable stateful logic without inheritance.

More Objects Questions

EasyHow does prototypal inheritance work in JavaScript?→EasyWhat is the difference between shallow copy and deep copy?→MediumWhat are property descriptors and property flags (writable, enumerable, configurable)?→EasyWhat are getters and setters in JavaScript?→

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint