🟑 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