25 min·intermediate

Lesson 7

Classes & inheritance

Build a practical mental model for classes & inheritance and use it in working JavaScript.

By the end, you will be able to…

  • Explain classes & inheritance in your own words
  • Use classes & inheritance in a small program
  • Recognize and debug a common failure mode

Build the mental model

class syntax is a cleaner way to write constructor functions and prototype-based inheritance. extends lets a subclass reuse a parent's behavior and override specific methods.

Syntax and working example

Read the code from inputs to output. Predict what it prints, then run it and change one value.

Working example
Expected output: Rex barks

Why this matters

Classes give a familiar, structured way to model related objects (Animal, Dog, Cat) that share behavior but differ in specifics.

Real-world example

UI component libraries and game entities (Player extends Character) commonly use exactly this class-and-inheritance structure.

Common mistakes

  • Forgetting to call super(...) in a subclass constructor before using `this`
  • Overusing inheritance for code reuse when composition (small combined objects) would be simpler
  • Forgetting that methods are shared on the prototype, not copied onto every instance

Try it yourself

Challenge

Add a Cat subclass that overrides speak() to return '<name> meows'.

Practice

Knowledge check

What must a subclass constructor call before using `this`?

Summary

Classes structure constructor-and-prototype patterns cleanly; extends enables inheritance and method overriding.