Classes

Syntax over the prototype mechanism — public and private fields, methods on the shared prototype, and extends for inheritance.

                class Name { #field; constructor() {} method() {} }
              

Purpose

A class is syntax over the prototype mechanism: its methods are placed on the class’s prototype, exactly as with Object.create or a constructor function, and extends sets up delegation between the child and parent prototypes. Private fields (#name) are a capability the older patterns couldn’t provide at all.

Syntax

class Animal {
  #energy = 100; // private field — inaccessible outside this class, even syntactically

  constructor(name) {
    this.name = name; // public field
  }

  speak() {
    return `${this.name} makes a sound.`;
  }
}

class Dog extends Animal {
  speak() {
    return `${this.name} barks.`; // overrides Animal's speak
  }
}

const rex = new Dog('Rex');
rex.speak(); // "Rex barks."
rex instanceof Animal; // true

Behavior notes

  • A class declaration is hoisted like let/const — in the temporal dead zone until its own line runs, unlike a function declaration.
  • super.methodName() inside a subclass method calls the parent class’s version explicitly; super() in a subclass constructor must run before this can be used, since it’s what actually constructs the parent portion of the instance.
  • A private field (#name) is enforced by the language itself — code outside the class can’t read, write, or even check for its existence, unlike a naming convention (_name) which is just a hint.
  • Class methods are non-enumerable by default (unlike a plain object’s methods), so they don’t show up in a for...in loop or Object.keys() over an instance.

Common mistakes

  • Reaching for extends purely for convenience when the relationship isn’t a genuine “is a” — see Objects, Prototypes, Classes, and this for why composition is often the better fit.
  • Forgetting super() in a subclass constructor before using this, which throws a ReferenceError.

Runtime notes

Classes (ES2015) and private fields (ES2022) are core ECMAScript, identical across every current browser and Node version.

Taught in these lessons

Related reference