JavaScript · Lesson 6

Classes

How class syntax builds constructor functions and prototypes for you, and how to use fields, private members, static members, getters, extends and super well, plus when composition or a mixin beats inheritance.

11 min read

In short

  • A class is a constructor function plus a prototype
  • Fields are per instance; methods are shared
  • #private is real privacy; getters give read-only views
  • extends links instances and statics
  • Keep this attached when passing methods around
  • Prefer composition; keep hierarchies shallow

class arrived in ES2015, and it looks a lot like C#. Underneath it's the same machinery as the Objects and Prototypes topic: a class is a constructor function, its methods live on ClassName.prototype, and instances find them through the prototype chain. Knowing that explains almost every class surprise: lost this, methods missing from JSON.stringify, static fields shared in odd ways, and instanceof failing across iframes.

Every js snippet has a ▶ Try button. Predict the output, then run it.

A class is a function plus a prototype

▶ Try
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  length() {
    return Math.hypot(this.x, this.y);
  }
}

const p = new Point(3, 4);
console.log(typeof Point);                                    // a function
console.log(Object.getPrototypeOf(p) === Point.prototype);    // the same link as before classes
console.log(Object.hasOwn(p, 'length'), Object.hasOwn(Point.prototype, 'length'));
console.log(Object.keys(p));                                  // only the data

That's the same structure as the constructor function version from the previous topic. What class adds on top:

  • It must be called with new. Point(1, 2) throws a TypeError instead of quietly writing to the global object.
  • The body is always strict mode, even in an old script.
  • Methods are not enumerable, so for...in and Object.keys only show data.
  • Class declarations are not hoisted like functions. Using a class before its declaration line throws a ReferenceError (the temporal dead zone, as with let).
  • extends and super wire both prototype chains for you (instances and statics).
  • Fields, private #members, static blocks and accessors have real syntax.

Constructors and fields

▶ Try
class Cart {
  items = [];                     // a public field: an own property of every instance
  currency = 'EUR';
  createdAt = new Date(0);        // evaluated again for each new instance

  constructor(owner) {
    this.owner = owner;           // fields already exist when the constructor body runs
  }

  add(sku, price) {
    this.items.push({ sku, price });
    return this;                  // returning this allows chaining
  }

  get total() {
    return this.items.reduce((sum, item) => sum + item.price, 0);
  }
}

const cart = new Cart('ann').add('pen', 2).add('ink', 5);
console.log(cart.total, Object.keys(cart));
console.log(new Cart('bob').items === cart.items);  // each instance gets its own array
  • A field (items = []) is created on each instance, before the constructor body runs. Its initializer runs once per instance, so every cart gets its own array. Compare that with putting an array on the prototype, where all instances would share one.
  • A method (add() {}) is created once, on the prototype, and shared.
  • A getter (get total()) is also on the prototype. It reads like a field but is computed. It isn't an own property, so Object.keys and JSON.stringify skip it.

Losing this

A method doesn't remember its object. this is whatever is left of the dot at the call:

▶ Try
class Counter {
  count = 0;
  increment() {
    this.count++;
  }
  incrementArrow = () => {        // an arrow function field: one per instance, `this` fixed
    this.count++;
  };
}

const c = new Counter();
const { increment, incrementArrow } = c;

try {
  increment();                    // called with no object: `this` is undefined
} catch (e) {
  console.log(e.constructor.name, e.message);
}
incrementArrow();                 // fine: the arrow captured `this` when the instance was built
console.log(c.count);

This is what bites you with button.addEventListener('click', this.save), setTimeout(this.tick, 100) and promise.then(this.handle). Fixes: an arrow function at the call site (() => this.save()), this.save.bind(this) once in the constructor, or an arrow function field. Arrow fields cost one function per instance and aren't on the prototype, so subclasses can't call them with super. Use them for callbacks, and normal methods for everything else.

Private members

#name makes a member truly private: it can't be read, written or even detected from outside the class body. That's enforced by the engine at runtime, unlike TypeScript's private, which disappears after compilation.

▶ Try
class Account {
  #balance = 0;                       // private field
  static #instances = 0;              // private static field

  constructor(owner) {
    this.owner = owner;
    Account.#instances++;
  }

  deposit(amount) {
    this.#check(amount);
    this.#balance += amount;
  }

  #check(amount) {                    // private method
    if (!(amount > 0)) throw new RangeError('amount must be positive');
  }

  get balance() {
    return this.#balance;
  }

  static count() {
    return Account.#instances;
  }

  static isAccount(value) {
    return #balance in value;         // "brand check": was this object built by Account?
  }
}

const acc = new Account('ann');
acc.deposit(50);
console.log(acc.balance, Object.keys(acc), JSON.stringify(acc));
console.log(acc.balance === 50, acc['#balance']);   // the string key '#balance' is unrelated
console.log(Account.isAccount(acc), Account.isAccount({ balance: 50 }), Account.count());
  • Private names are scoped to the class body. Even a subclass can't read its parent's #balance. Expose what subclasses need through methods or getters.
  • Reading a private field from an object that doesn't have it throws a TypeError. #field in obj checks without throwing. That makes it a reliable "is this a real instance?" test, stronger than instanceof, because a fake object with the right prototype still has no private fields.
  • Private fields don't appear in Object.keys, JSON.stringify, spread or structuredClone (debuggers such as Chrome DevTools still display them). A class with private state needs its own toJSON() and clone().

Static members and static blocks

static members belong to the class itself, not to instances: factories, constants, caches, registries.

▶ Try
class Temperature {
  static ABSOLUTE_ZERO = -273.15;
  static #cache = new Map();

  static {
    // A static block runs once, when the class is defined. Use it for setup that needs statements.
    for (const c of [0, 100]) Temperature.#cache.set(c, new Temperature(c));
  }

  static of(celsius) {
    return Temperature.#cache.get(celsius) ?? new Temperature(celsius);
  }

  constructor(celsius) {
    if (celsius < Temperature.ABSOLUTE_ZERO) throw new RangeError('below absolute zero');
    this.celsius = celsius;
  }
}

console.log(Temperature.of(100) === Temperature.of(100), Temperature.of(37) === Temperature.of(37));
console.log(Temperature.ABSOLUTE_ZERO, new Temperature(20).ABSOLUTE_ZERO);

Inside a static method, this is the class it was called on. That makes static create() { return new this(); } build the right subclass. It also produces one of the trickiest class bugs, shown in the extends section below.

extends and super

▶ Try
class Shape {
  constructor(name) {
    this.name = name;
  }
  area() {
    return 0;
  }
  describe() {
    return `${this.name} with area ${this.area().toFixed(2)}`;
  }
}

class Circle extends Shape {
  constructor(radius) {
    super('circle');          // must run before any use of `this`
    this.radius = radius;
  }
  area() {                    // override
    return Math.PI * this.radius ** 2;
  }
}

class Ring extends Circle {
  constructor(outer, inner) {
    super(outer);
    this.inner = inner;
    this.name = 'ring';
  }
  area() {
    return super.area() - Math.PI * this.inner ** 2;   // call the parent version
  }
}

const shapes = [new Circle(1), new Ring(2, 1)];
for (const s of shapes) console.log(s.describe());
console.log(shapes[1] instanceof Circle, shapes[1] instanceof Shape);
console.log(Object.getPrototypeOf(Ring.prototype) === Circle.prototype, Object.getPrototypeOf(Ring) === Circle);
  • extends links two chains: Ring.prototype → Circle.prototype → Shape.prototype for instance methods, and Ring → Circle → Shape for statics. That's what the Inheritance without class exercise builds by hand.
  • In a derived class, super(...) creates the object. Touching this before it throws a ReferenceError. If you don't write a constructor, you get constructor(...args) { super(...args); }.
  • super.method() calls the parent's version with the current this. Overriding is just shadowing: the subclass prototype has its own area, so the lookup stops there. Every method is "virtual"; there is no override or sealed at runtime.
  • describe in Shape calls this.area(), and gets the subclass version. That's polymorphism through the prototype chain.

Initialization order (an interview favourite)

▶ Try
class Base {
  greeting = 'hello';
  constructor() {
    console.log('Base constructor sees:', this.describe());
  }
  describe() {
    return this.greeting;
  }
}

class Derived extends Base {
  name = 'Derived';
  describe() {
    return `${this.greeting} from ${this.name}`;   // name isn't set yet when Base calls this!
  }
}

console.log('after construction:', new Derived().describe());

The order for new Derived() is: Base fields → Base constructor body → Derived fields → Derived constructor body. The Base constructor calls the overridden describe, which reads this.name before Derived's fields exist. C# has the same trap with virtual calls in constructors. Rule: don't call overridable methods from a constructor.

Static state and inheritance

▶ Try
class Model {
  static count = 0;
  static create() {
    this.count++;              // `this` is whichever class create() was called on
    return new this();
  }
}
class User extends Model {}

User.create();
User.create();
Model.create();
console.log(Model.count, User.count, Object.hasOwn(User, 'count'));

User.count++ reads count through the static chain (finding Model.count, 0) and writes a new own count on User. Reads walk the chain, writes don't, just like with instances. If you want one counter per subclass, make that explicit (a Map keyed by class, or Object.hasOwn(this, 'count')); if you want one shared counter, write Model.count++.

instanceof

x instanceof C asks: is C.prototype anywhere on x's prototype chain? It doesn't care how x was made:

▶ Try
class Animal {}
class Dog extends Animal {}

const fake = Object.create(Dog.prototype);         // never ran a constructor
console.log(new Dog() instanceof Animal, fake instanceof Dog);
console.log({} instanceof Animal, Object.create(null) instanceof Object);
  • It fails across realms: an array from an iframe or a vm context isn't instanceof Array in yours. That's why Array.isArray exists.
  • Two copies of a library in one bundle (two versions in node_modules) give you two different classes with the same name, and instanceof says false. Duck typing or a brand check (#x in obj) is more robust at boundaries.

Extending built-ins

You can extend Error, Array, Map, EventTarget and friends. Error is the one you'll do most:

▶ Try
class HttpError extends Error {
  constructor(status, message, options) {
    super(message, options);          // options can carry { cause }
    this.name = 'HttpError';
    this.status = status;
  }
  get isRetryable() {
    return this.status === 429 || this.status >= 500;
  }
}

class NotFoundError extends HttpError {
  constructor(resource) {
    super(404, `${resource} not found`);
    this.name = 'NotFoundError';
  }
}

try {
  throw new NotFoundError('order 42');
} catch (e) {
  console.log(e instanceof NotFoundError, e instanceof HttpError, e instanceof Error);
  console.log(String(e), e.status, e.isRetryable);
}

Set name, or e.name, String(e) and the stack trace say plain Error. Pass { cause } to keep the original error when you wrap one. The Error hierarchy exercise goes further.

Composition, inheritance and mixins

Inheritance says "a Ring is a Circle". It couples the subclass to the parent's internals and initialization order, and JavaScript allows only one parent. Most of the time composition, "a Report has a Formatter", is simpler to change and to test:

▶ Try
class ConsoleLogger {
  log(message) {
    console.log(`[log] ${message}`);
  }
}

class OrderService {
  #logger;
  constructor(logger) {
    this.#logger = logger;            // the dependency is passed in: easy to swap in tests
  }
  place(id) {
    this.#logger.log(`order ${id} placed`);
    return { id, status: 'placed' };
  }
}

console.log(new OrderService(new ConsoleLogger()).place(7).status);

That's also how Angular's dependency injection works: services are classes, and they receive their dependencies through the constructor.

When several unrelated classes need the same behaviour, a mixin is a function that takes a class and returns a subclass of it:

▶ Try
const Timestamped = (Base) => class extends Base {
  createdAt = new Date('2024-01-01T00:00:00Z');
  touch() {
    this.updatedAt = new Date('2024-01-02T00:00:00Z');
    return this;
  }
};

const Serializable = (Base) => class extends Base {
  toJSON() {
    return { type: this.constructor.name, ...this };
  }
};

class Entity {
  constructor(id) {
    this.id = id;
  }
}

class Invoice extends Serializable(Timestamped(Entity)) {}

const invoice = new Invoice(1).touch();
console.log(JSON.stringify(invoice));
console.log(invoice instanceof Entity);

Each mixin adds one layer to the prototype chain, so super calls compose. Keep mixins small and independent. Many teams prefer plain composition, or functions over data, before reaching for them.

Coming from C# and TypeScript

Side note
  • No overloading. One constructor, one method per name. Use optional parameters, an options object, or static factories (Money.fromCents, Money.parse).
  • No interfaces, abstract or sealed at runtime. TypeScript has abstract and interface, and both disappear after compilation. To stop a base class being created directly at runtime, check if (new.target === Shape) throw new TypeError(...).
  • TypeScript private is compile time only. obj['secret'] still reads it, and it shows up in JSON. #secret is real privacy. Prefer # in new code unless a framework needs the field visible (some decorators and serializers do).
  • No parameter properties or readonly at runtime. constructor(private readonly repo: Repo) is TypeScript sugar for a field plus an assignment.
  • Every method is virtual, and this depends on the call, not the class. Passing obj.method around detaches it.
  • No struct semantics or value equality. Two instances with equal fields are not ===. Write an equals method, as you would override Equals in C#.

In real codebases

Side note
  • Angular is class-based: components, services, guards and pipes are classes, with dependencies passed into the constructor (or read with inject()). Understanding fields, this and initialization order matters there daily.
  • React moved from class components to function components with hooks. You'll still meet class components in older code, and error boundaries still need a class.
  • Errors are the class hierarchy almost every codebase has: ValidationError, HttpError, NotFoundError, checked with instanceof in error handlers and middleware.
  • Domain objects (money, date ranges, ids) benefit from classes with private state, validation in the constructor and immutability. Plain objects plus functions are often enough for everything else.
  • Prefer shallow hierarchies. One level of extends is common, two is a smell, three is a refactor waiting to happen. Composition, mixins and plain functions keep code easier to change.

The exercises

  1. Bank account: private state, validation and a read-only getter.
  2. Shape hierarchy: an abstract base, overriding, super and a static comparator.
  3. LRU cache class: a Map-backed cache with a clean public API.
  4. Observable store: subscribe, unsubscribe and immutable state updates.
  5. Error hierarchy: custom errors with name, cause and instanceof.
  6. Mixins: reusable behaviour layered onto unrelated classes.
  7. Money value class: private constructor, brand checks and immutable arithmetic.
  8. Model base class: static fields per subclass, new this and inherited schemas.

Practise this lesson

In the app: a short video, 8 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.

Open in the app