Core Language

JavaScript Classes

Classes are syntactic sugar over JavaScript's prototype-based inheritance. They provide a clean, readable way to create objects with shared behaviour, private state, inheritance, and static utilities.

How do classes work in JavaScript?

A class is a template for creating objects with the same shape and methods. Define a constructor to set up each instance, add methods, and create instances with new. Use extends to inherit from another class and super to call the parent. Fields starting with # are truly private.

class Account {
  #balance = 0;                       // private field
  constructor(owner) { this.owner = owner; }
  deposit(amount) { this.#balance += amount; return this; }
  get balance() { return this.#balance; }
  static create(owner) { return new Account(owner); }
}
class Savings extends Account {
  constructor(owner, rate) { super(owner); this.rate = rate; }
}

What is a Class?

A class is a blueprint for creating objects. It bundles data (properties) and behaviour (methods) together. Under the hood, JavaScript classes use prototypes — the syntax is just cleaner and more structured.

  • Defined with the class keyword
  • constructor() runs when new is called
  • Methods shared via prototype (memory-efficient)
  • Supports private fields with # prefix (ES2022)
  • Extends enables single inheritance

Class Anatomy

class Vehicle {
#speed = 0; // private field
static count = 0; // class field
constructor(make) {
this.make = make;
Vehicle.count++;
}
get speed() { return this.#speed; }
accelerate(n) { this.#speed += n; }
}

Inheritance with extends & super

extends lets a child class inherit all public and protected members from a parent. super() calls the parent constructor and must be called before using this in the child constructor.

super() in constructor

Invokes the parent class constructor. Required before accessing this.

super.method()

Calls the parent version of an overridden method from within the child.

instanceof check

An instance of a child class is also an instance of the parent class.

Private Fields & Encapsulation

The # prefix makes a field truly private — it cannot be accessed or modified from outside the class, not even by subclasses. This enforces encapsulation at the language level (not just by convention).

  • Declared at the top of the class body
  • Accessible only within the defining class
  • Throws SyntaxError if accessed from outside
  • Subclasses cannot access parent private fields
  • Use getters/setters to expose controlled access
class BankAccount {
#balance = 0; // private
deposit(amt) {
this.#balance += amt;
}
get balance() {
return this.#balance;
}
}
// acc.#balance → SyntaxError ✗
// acc.balance → OK ✓

Static Fields & Methods

Static members belong to the class itself, not to any instance. They are useful for utility functions, factory methods, constants, and singleton patterns.

static count = 0Shared counter across all instances
static create(...args)Factory: construct instances with defaults
static #instancePrivate static for Singleton pattern
static defaults = {...}Shared config object for all instances

Key Rules

  • • Called as ClassName.method(), not instance.method()
  • • Cannot use this to refer to an instance
  • • Inherited by subclasses
  • • Great for utility/helper functions attached to a concept

Mixins — Composing Behaviours

JavaScript only supports single inheritance, but mixins let you compose multiple behaviours by wrapping classes in higher-order functions. This is often preferable to deep inheritance chains.

// Mixin: add serialization to any class
const Serializable = (Base) => class extends Base {
serialize() { return JSON.stringify(this); }
}
// Compose multiple mixins
class User extends Serializable(Timestamped(Person)) {
// User now has: greet(), serialize(), createdAt
}

Common Pitfalls

Forgetting super() in child constructor
Always call super() before using this in a subclass constructor
Using class methods as callbacks (losing this)
Bind in constructor or use arrow function class fields: method = () => {}
Deep inheritance chains (3+ levels)
Prefer composition/mixins for sharing behaviour across unrelated classes
Putting everything in the constructor
Use private fields for state, move logic to methods for clarity and testability

Interactive Examples

Run the code to see classes, inheritance, private fields, static methods, and mixins in action. Modify freely to experiment.

Code Editor

<pre id="out"></pre>

Preview

JavaScript classes — step by step

1 / 4
1

Class syntax is sugar over prototypes

class Foo { constructor() {} method() {} } is equivalent to a constructor function with Foo.prototype.method = function() {}. Classes do not introduce a new OOP model — they are a cleaner syntax for the same prototype-based system. Methods defined in the class body are placed on the prototype, not on each instance.

1 of 4
💡Avoid deep class hierarchies
More than 2-3 levels of class inheritance creates fragile, tightly coupled code. Changes to a base class can unexpectedly break all subclasses. Prefer composition: small focused mixins combined to create complex behavior. Use extends only when there is a clear, stable is-a relationship that will not change.

🎯 Quick Check

Where are methods defined in a class body stored?

JavaScript Classes: summary

Key points

  • Classes are syntax over prototypes; methods live on the prototype and are shared.
  • Class bodies run in strict mode, and classes aren't hoisted like function declarations.
  • static members belong to the class itself, not to instances.
  • Prefer composition (objects containing other objects) over deep inheritance chains.

Frequently asked questions

›Are JavaScript classes real classes?

They behave like classes in other languages for most purposes, but under the hood they're built on prototypal inheritance.

›How do I make a private property?

Prefix it with # (#balance). It can only be accessed inside the class body.