Code of the Day
IntermediateThe runtime

Classes and prototypes

Model objects with shared behaviour — the class syntax and what sits underneath it.

JavaScript / TSIntermediate9 min read
Recommended first
By the end of this lesson you will be able to:
  • Define a class with a constructor and methods
  • Create instances and use this
  • Understand that classes are sugar over prototypes

A class is a template for objects that share structure and behaviour. JS class syntax looks much like other languages, but underneath sits JavaScript's own model — worth knowing so the language stops surprising you.

Defining a class

constructor runs when you create an instance; methods are shared by all instances. this refers to the instance:

class Counter {
  constructor(start = 0) {
    this.count = start;     // an instance field
  }
  increment() {
    this.count += 1;
  }
  value() {
    return this.count;
  }
}

const c = new Counter();    // `new` creates an instance
c.increment();
c.value();                  // 1

new makes a fresh object, runs the constructor with this bound to it, and hands it back. Each instance has its own count.

JavaScript — editable, runs in your browser

Sugar over prototypes

Under the hood, JavaScript doesn't have classes the way some languages do — it has prototypes. Every object has a hidden link to a prototype object, and method lookups that miss on the instance fall back to it. When you define a method on a class, it actually lives on the shared prototype, which is why all instances can use it without each storing its own copy. class is friendlier syntax over this mechanism.

A note on this

this depends on how a function is called, not where it's defined — a frequent source of bugs when passing methods as callbacks. Arrow functions don't have their own this (they close over the surrounding one), which is exactly why they're handy for callbacks inside methods.

As in Python: don't reach for a class by default. Plain objects and functions cover most needs; use a class when you have many objects sharing the same structure and behaviour.

Where to go next

Next: error handling — try/catch, throwing, and failing safely.

Finished reading? Mark it complete to track your progress.

On this page