JavaScript - Inheritance & Mixins

Overview

Estimated time: 35–45 minutes

Compose behavior with class inheritance (extends) and/or mixins (function-based composition). Prefer shallow inheritance trees and favor composition for flexible reuse.

Learning Objectives

  • Use extends and super() for inheritance.
  • Apply mixins to add reusable capabilities.

Prerequisites

Class inheritance

class Shape { area(){ return 0; } }
class Rect extends Shape {
  constructor(w, h){ super(); this.w = w; this.h = h; }
  area(){ return this.w * this.h; }
}
new Rect(2,3).area(); // 6

Mixin pattern

const CanLog = (Base) => class extends Base {
  log(msg){ console.log(`[${this.constructor.name}]`, msg); }
};

class Model {}
class User extends CanLog(Model) {
  constructor(name){ super(); this.name = name; }
}
new User('Ada').log('created');

Common Pitfalls

  • Deep inheritance hierarchies are brittle; prefer composition/mixins.
  • Mixins may conflict on method names; establish naming conventions.