class Under the Hood

class is elegant syntax over prototypes -- plus real private fields, statics and super.

Syntaxclass C extends P { #secret = 0; static make() {} get value() {} }

A class is largely sugar over the prototype machinery from the last lesson. Methods you declare land on Class.prototype; the constructor becomes the function you call with new; extends wires one prototype to another.

class Animal {
  constructor(name) { this.name = name; }
  speak() { return `${this.name} makes a sound`; }
}
class Dog extends Animal {
  speak() { return `${super.speak()} (woof)`; }
}

What classes add beyond prototypes

  • Real privacy with #fields -- unreachable from outside, enforced by the language, not a naming convention.
  • static members on the class itself, and static blocks for setup.
  • super to reach the parent's constructor and methods.
  • Bodies always run in strict mode and are not hoisted (they sit in a TDZ).

Getters, setters, fields

Class fields, accessor get/set, and #-private methods make classes a genuinely full OOP tool, while still being prototypes underneath.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Define a private balance field on a BankAccount class so it cannot be read or modified externally.
  • Use static class methods for utility functions that operate on the class itself rather than instances.
  • Extend a base Component class to add lifecycle hooks in a UI framework.

More examples

Class with private field

Uses the # prefix to declare a private field that is truly inaccessible from outside the class.

Example · js
class BankAccount {
  #balance = 0;
  deposit(amount) { this.#balance += amount; }
  get balance() { return this.#balance; }
}
const acc = new BankAccount();
acc.deposit(100);
console.log(acc.balance);  // 100
// acc.#balance;           // SyntaxError

Static method

Defines a static method on the class itself rather than on instances, called without new.

Example · js
class MathUtils {
  static clamp(value, min, max) {
    return Math.min(Math.max(value, min), max);
  }
}
console.log(MathUtils.clamp(150, 0, 100)); // 100

Class inheritance with super

Extends Shape with super() to initialise the parent's color property and adds a Circle-specific area method.

Example · js
class Shape {
  constructor(color) { this.color = color; }
  describe() { return `A ${this.color} shape`; }
}
class Circle extends Shape {
  constructor(color, radius) {
    super(color);
    this.radius = radius;
  }
  area() { return Math.PI * this.radius ** 2; }
}
const c = new Circle("red", 5);
console.log(c.describe(), c.area().toFixed(2));

Discussion

  • Be the first to comment on this lesson.
class Under the Hood — JavaScript | SoundsCode