JavaScript Tutorial: Inheritance
Extend classes with extends and super, override methods, use instanceof, and know when NOT to use inheritance.
Build on what exists
Inheritance lets you create specialised versions of existing classes without copying code. `AdminUser` gets everything `User` has, then adds its own capabilities.
JavaScript's class inheritance is prototype-based under the hood — the `extends` keyword sets up the prototype chain. Chapter 14 goes deeper on that.
What you'll learn in this JavaScript inheritance tutorial
This interactive JavaScript tutorial has 7 hands-on exercises. Estimated time: 18 minutes.
- extends — inherit everything — When class B extends class A, B gets all of A's methods for free. You only add what's different.
- super() — call the parent constructor — When a child class has its own constructor, you **must** call `super()` first — before accessing `this`.
- Override — replace the parent's method — A child class replaces a parent method by defining it with the same name.
- instanceof — type checking — `instanceof` checks if an object is an instance of a class — or any of its ancestors:
- Abstract-like patterns — JavaScript doesn't have `abstract` classes, but you can simulate them by throwing in the base class method:
- Composition over inheritance — Inheritance creates tight coupling. Deep inheritance hierarchies are notoriously hard to maintain.
- Build an animal hierarchy — Final challenge — no starter code.
JavaScript Inheritance concepts covered
- Build on what exists