Skip to content

Lesson 11 of 50JavaScript in depth

Classes and Prototypes

Write classes with private fields, getters, statics and inheritance, and see the prototype chain they are built on.

27 min read0/7 questions

You will meet classes in Node services, in error handling (class NotFoundError extends Error), in SDKs like the AWS and Stripe clients, and all over TypeScript codebases. Underneath, JavaScript classes are a friendlier syntax over prototypes, and knowing that explains how methods are shared, what instanceof checks, and why this behaves the way it does.

A class

A class is a blueprint for objects. The constructor runs when you create an instance with new, and methods are defined once and shared by every instance.

JavaScript
class Timer { constructor(label, seconds = 0) { this.label = label; this.seconds = seconds; } tick() { this.seconds += 1; return this; // returning this allows chaining } describe() { return `${this.label}: ${this.seconds}s`; }} const t = new Timer("focus");t.tick().tick().tick();console.log(t.describe());console.log(typeof Timer, t instanceof Timer);
Output
Press Run (⌘ Enter) to see what happens.

A few rules that differ from Python: you must use new (calling Timer() without it throws a TypeError), there is no self parameter (you use this), and class bodies always run in strict mode. Class declarations are not hoisted the way function declarations are, so define a class before you use it.

Class fields, getters and setters

You can declare fields directly in the class body instead of assigning them in the constructor. A getter (get name()) runs a function when a property is read; a setter (set name(v)) runs when it is assigned. From outside they look like ordinary properties.

JavaScript
class Temperature { celsius = 0; // public class field with a default get fahrenheit() { return this.celsius * 1.8 + 32; } set fahrenheit(value) { this.celsius = (value - 32) / 1.8; }} const temp = new Temperature();temp.celsius = 100;console.log(temp.fahrenheit); // no parentheses: it is a gettertemp.fahrenheit = 32;console.log(temp.celsius);
Output
Press Run (⌘ Enter) to see what happens.

Private fields and static members

Before 2022, "private" in JavaScript meant naming a property _balance and hoping nobody touched it. Private fields start with # and are enforced by the language: code outside the class body cannot read or write them at all.

JavaScript
class Wallet { #balance = 0; // truly private static #count = 0; // private and shared by the class itself constructor(owner) { this.owner = owner; Wallet.#count += 1; } deposit(amount) { if (amount <= 0) throw new Error("Amount must be positive"); this.#balance += amount; } get balance() { return this.#balance; } static created() { return Wallet.#count; }} const w = new Wallet("Priya");w.deposit(50);console.log(w.balance);console.log(w.secret, Object.keys(w)); // #balance is invisibleconsole.log(Wallet.created()); try { w.deposit(-5);} catch (e) { console.log(e.message);}
Output
Press Run (⌘ Enter) to see what happens.

A static member belongs to the class, not to instances: Wallet.created(), Math.max, Array.from, Promise.all. Use statics for factory functions (User.fromJSON(data)) and helpers that do not need an instance. Methods can be private too (#validate()).

Quick check
What happens when code outside the class runs w.#balance = 1000?
Need a nudge? A hint rules out a wrong answer.

Inheritance with extends and super

class Child extends Parent makes a subclass. Inside the child, super(...) calls the parent's constructor (you must call it before touching this), and super.method() calls the parent's version of a method you are overriding.

JavaScript
class Shape { constructor(name) { this.name = name; } area() { return 0; } describe() { return `${this.name} with area ${this.area().toFixed(1)}`; }} class Circle extends Shape { constructor(radius) { super("circle"); // run Shape's constructor first this.radius = radius; } area() { return Math.PI * this.radius ** 2; // override }} class Square extends Shape { constructor(side) { super("square"); this.side = side; } area() { return this.side ** 2; } describe() { return super.describe() + " (all sides equal)"; // extend the parent's version }} for (const s of [new Circle(1), new Square(3)]) console.log(s.describe());console.log(new Square(2) instanceof Shape);
Output
Press Run (⌘ Enter) to see what happens.

Notice that Shape.describe calls this.area(), and each subclass's own area runs. That is polymorphism: the same call does the right thing for each type.

The most common real use of extends is custom errors:

JavaScript
class NotFoundError extends Error { constructor(resource) { super(`${resource} not found`); this.name = "NotFoundError"; this.status = 404; }} try { throw new NotFoundError("User 42");} catch (e) { console.log(e instanceof NotFoundError, e instanceof Error); console.log(e.name, e.status, e.message);}
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputJavaScript

What does this print?

class Animal {
speak() { return "..."; }
intro() { return "I say " + this.speak(); }
}
class Dog extends Animal {
speak() { return "woof"; }
}
console.log(new Dog().intro());
Need a nudge? Hints walk you through it.

Under the hood: prototypes

JavaScript did not have classes until 2015. Instead, every object has a hidden link to another object, its prototype. When you read a property that the object does not have, the engine follows that link and looks there, then at that object's prototype, and so on until it reaches null. This is the prototype chain.

class builds exactly this. Methods live on ClassName.prototype, one copy shared by all instances, and extends links one prototype to the next.

The prototype chain for new Circle(1)
nullcircleown data: name, radiusCircle.prototypearea (override), constructorShape.prototypedescribe, areaObject.prototypetoString, hasOwnPropertyroot

The instance holds only its own data: name and radius. No methods are copied into it.

1/4
JavaScript
class Shape { describe() { return "a shape"; }}class Circle extends Shape {}const c = new Circle(); console.log(Object.getPrototypeOf(c) === Circle.prototype);console.log(Object.getPrototypeOf(Circle.prototype) === Shape.prototype);console.log(Object.hasOwn(c, "describe"), "describe" in c);console.log(c.describe === new Circle().describe); // one shared function
Output
Press Run (⌘ Enter) to see what happens.

instanceof walks this same chain: c instanceof Shape is true because Shape.prototype appears somewhere above c. You can even create objects with a chosen prototype and no class at all, using Object.create(proto). Arrays get map and filter the same way, from Array.prototype.

Quick check
You create 10,000 Circle instances. How many copies of the area method exist in memory?
Need a nudge? A hint rules out a wrong answer.

Object.create and property lookup in depth

Classes hide the prototype machinery. Object.create(proto) exposes it: it makes a new, empty object whose prototype is exactly the object you pass. No constructor, no new, no class. It is the clearest way to see how reads and writes really behave.

JavaScript
const animal = { legs: 4, describe() { return `${this.name} has ${this.legs} legs`; },}; const bird = Object.create(animal); // bird's prototype is animalbird.name = "Robin";bird.legs = 2; // assignment creates an OWN property that shadows animal.legs console.log(bird.describe());console.log(Object.hasOwn(bird, "legs"), Object.hasOwn(bird, "describe"));console.log(animal.legs); // the prototype is untouched const dog = Object.create(animal);dog.name = "Rex";console.log(dog.describe()); // reads legs from the prototype // Inherited enumerable properties show up in for...in, not in Object.keysconst keys = [];for (const k in bird) keys.push(k);console.log(keys, Object.keys(bird)); // A dictionary with no prototype at allconst counts = Object.create(null);counts["constructor"] = 1;console.log("toString" in counts, counts.constructor);const plain = {};console.log("toString" in plain, typeof plain.constructor);
Output
Press Run (⌘ Enter) to see what happens.

The key insight is that reads and writes are not symmetric:

  • A read walks the chain: own property first, then the prototype, then its prototype, until null.
  • A write (obj.x = 1) normally creates or updates an own property on obj. It does not walk up and change the prototype. Setting bird.legs gave bird its own legs that shadows the inherited one, and dog still sees 4.

That second rule has two exceptions, and they are the source of real confusion. If a prototype up the chain has a setter for that name, the write calls the setter instead of creating an own property. If it has a read-only property of that name, the write is refused: silently in sloppy mode, with a TypeError in strict mode (which includes all class bodies and modules).

JavaScript
const base = { _size: 0, set size(v) { this._size = v * 2; },};Object.defineProperty(base, "version", { value: 3, writable: false }); const child = Object.create(base);child.size = 5; // no own "size" is created: the inherited setter runsconsole.log(Object.hasOwn(child, "size"), child._size, base._size); function tryWrite() { "use strict"; child.version = 4; // inherited read-only property blocks the write}try { tryWrite();} catch (e) { console.log(e.name, child.version);}
Output
Press Run (⌘ Enter) to see what happens.

Notice child._size is 10 but base._size is still 0. The setter ran with this set to child, so its own write landed on child. Methods found on a prototype always run with this as the object you called them on, which is exactly why one shared method can serve thousands of instances.

Two practical uses of Object.create:

  • Object.create(null) gives a "pure dictionary" with no inherited keys. A plain {} inherits constructor, toString and friends, so "constructor" in counts is true for a plain object even when you never set it. When keys come from users (word counts, query parameters), a null-prototype object or a Map avoids those collisions. It also helps against prototype pollution, an attack where input like {"__proto__": {"isAdmin": true}} is merged into an object and ends up modifying Object.prototype for the whole app.
  • Explicit prototypes in tests and old code. Before class, inheritance was Child.prototype = Object.create(Parent.prototype). You will still see it in older libraries and transpiled output.

Know the difference between the two membership checks: Object.hasOwn(obj, key) looks only at the object itself, while key in obj walks the chain. for...in also walks the chain (enumerable properties only), which is why modern code uses Object.keys or Object.entries. Class methods are non-enumerable, so they never show up in either.

Predict the outputJavaScript

What does this print?

const proto = { count: 0, bump() { this.count += 1; } };
const a = Object.create(proto);
const b = Object.create(proto);
a.bump();
a.bump();
b.bump();
console.log(a.count, b.count, proto.count);
Need a nudge? Hints walk you through it.

Getters and setters in depth

The Temperature class at the start used a getter and a setter for unit conversion. On the job they do three jobs: computed values (fullName, isOverdue), validation on write, and read-only views of private state. Pair a setter with a #private backing field and the class can enforce its own rules:

JavaScript
class Temperature { #celsius = 0; get celsius() { return this.#celsius; } set celsius(value) { if (typeof value !== "number" || Number.isNaN(value)) { throw new TypeError(`celsius must be a number, got ${value}`); } if (value < -273.15) throw new RangeError("below absolute zero"); this.#celsius = value; } get fahrenheit() { return this.#celsius * 1.8 + 32; }} const t = new Temperature();t.celsius = 25;console.log(t.celsius, t.fahrenheit); try { t.celsius = -300;} catch (e) { console.log(e.name, e.message);} try { t.fahrenheit = 100; // getter only: assignment fails} catch (e) { console.log(e.name);} // Getters live on the prototype, so copies and JSON miss themconsole.log(JSON.stringify(t), { ...t }, Object.keys(t));console.log(Object.getOwnPropertyNames(Temperature.prototype));
Output
Press Run (⌘ Enter) to see what happens.

Look at the last two lines. The getters are defined on Temperature.prototype, not on the instance, and the data is in a private field. So JSON.stringify, spread and Object.keys, which only look at own enumerable properties, see nothing at all. This is a frequent surprise when someone returns a class instance from an API handler and the client receives {}. The fix is a toJSON() method, which JSON.stringify calls if it exists, or mapping the instance to a plain object at the boundary.

A getter with no setter makes a property read-only. In class code (always strict) the assignment throws a TypeError, as above. In sloppy-mode scripts it is silently ignored, which is worse.

You can also define accessors on any object with Object.defineProperty(obj, "name", { get() {...}, enumerable: true }). That is how Vue 2 and early versions of MobX made objects "reactive": the getter records who read the value, the setter notifies them when it changes. Vue 3 and later MobX moved to Proxy, which intercepts every key, including new ones.

Where seniors draw the line: a getter should be cheap and have no side effects. Code reads order.total like a field and may call it in a loop or a render function. If it hits the network or does heavy work, make it a method (order.calculateTotal()) so the cost is visible at the call site.

instanceof across realms and Symbol.hasInstance

x instanceof C asks one question: does C.prototype appear anywhere on x's prototype chain? That is precise, and it fails in two situations you will meet at work.

Realms. Every window, iframe, worker and Node vm context is a separate realm with its own set of built-ins: its own Array, its own Error, its own Object.prototype. An array created inside an iframe has the iframe's Array.prototype in its chain, so iframeArray instanceof Array is false in the parent page, even though it is a perfectly normal array. Data that crosses realms by postMessage is cloned into the receiver's realm, so it is not affected; objects shared by reference are.

Duplicate copies of a class. The same thing happens without iframes when two versions of a package are installed. Your code imports HttpError from http-lib@2, a dependency throws one from http-lib@1, and err instanceof HttpError is false. Monorepos and bundles with duplicated dependencies hit this regularly.

JavaScript
// Two copies of the "same" class, as when two versions of a package are installedfunction loadHttpLib() { return class HttpError extends Error { constructor(status) { super(`HTTP ${status}`); this.name = "HttpError"; this.status = status; } };}const HttpErrorV1 = loadHttpLib();const HttpErrorV2 = loadHttpLib(); const err = new HttpErrorV1(404);console.log(err instanceof HttpErrorV1, err instanceof HttpErrorV2); // A duck-typed check that survives duplicates and realmsconst isHttpError = (e) => e instanceof Error && e.name === "HttpError" && typeof e.status === "number";console.log(isHttpError(err)); // Symbol.hasInstance lets a class decide what instanceof meansclass Even { static [Symbol.hasInstance](value) { return Number.isInteger(value) && value % 2 === 0; }}console.log(4 instanceof Even, 7 instanceof Even); // Array.isArray is realm-safe; instanceof Array is notconsole.log(Array.isArray([]), [] instanceof Array);
Output
Press Run (⌘ Enter) to see what happens.

The defences, from most to least preferred:

  • Use the realm-safe built-in checks. Array.isArray(x) works across realms. For errors there is the newer Error.isError(x), available in current Node and recent browsers (check support before relying on it). Object.prototype.toString.call(x) returning "[object Date]" is the old fallback.
  • Check a brand or a shape. A code or name field (err.code === "ERR_NOT_FOUND"), or a type guard that checks the properties you need. Node's own errors are designed to be checked by code, not by class.
  • Deduplicate dependencies so only one copy of the class exists. Your package manager can tell you why two versions are installed.

Symbol.hasInstance is the hook behind instanceof. A class can define a static method under that symbol, and x instanceof C calls it instead of walking the chain. Libraries use it to make instanceof work across their own duplicate copies, for example by checking a shared brand symbol registered with Symbol.for. In app code it is rare, and a custom instanceof that lies (like Even above) will confuse your teammates, so treat it as something to recognise rather than reach for.

Quick check
A page receives an array object from a same-origin iframe by reference (for example iframe.contentWindow.items). Which check returns true?
Need a nudge? A hint rules out a wrong answer.

When to skip classes

Classes are one tool, not the default. Modern JavaScript, and React in particular, leans toward plain objects and functions:

Reach forWhen
Plain object { ... }Data with no behaviour: API responses, config, props, state
Functions + closuresBehaviour with a little private state: makeCounter, createStore
A classMany instances sharing behaviour and private state, instanceof checks, custom errors, or an SDK-style API

Plain objects serialise to JSON cleanly, are easy to copy with spread, and do not lose this when you pass their functions around. Deep inheritance trees (Animal → Mammal → Dog → ServiceDog) are hard to change; prefer shallow hierarchies and composition (an object that has a helper rather than is one). React moved from class components to function components for these reasons.

Put it in order4 steps

Order what happens when you run new Circle(2) where Circle extends Shape.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Mixins vs composition

JavaScript classes have single inheritance: one extends. When several unrelated classes need the same behaviour (timestamps, serialisation, event emitting), people reach for mixins. In JavaScript a mixin is a function that takes a class and returns a subclass of it, which works because extends accepts any expression:

JavaScript
// A mixin is a function from a class to a subclassconst Timestamped = (Base) => class extends Base { createdAt = new Date("2026-10-22T09:00:00Z"); age(now) { return Math.round((now - this.createdAt) / 60000) + " min"; } }; const Serializable = (Base) => class extends Base { toJSON() { return { type: this.constructor.name, ...this }; } }; class Model { constructor(id) { this.id = id; }} class Invoice extends Serializable(Timestamped(Model)) {} const inv = new Invoice("inv_1");console.log(inv.age(new Date("2026-10-22T09:45:00Z")));console.log(JSON.stringify(inv));console.log(inv instanceof Model); // The chain the mixins builtlet proto = Object.getPrototypeOf(inv);const chain = [];while (proto) { chain.push(proto.constructor.name || "(anonymous)"); proto = Object.getPrototypeOf(proto);}console.log(chain.join(" -> "));
Output
Press Run (⌘ Enter) to see what happens.

The last line shows what a mixin really is: two extra, anonymous classes inserted into the prototype chain. That explains both the appeal and the problems:

  • Name clashes are silent. If two mixins both define toJSON or save, the outer one wins and the inner one is shadowed. Nothing warns you.
  • Order matters. Serializable(Timestamped(Model)) and Timestamped(Serializable(Model)) build different chains, and super.method() calls go to different places.
  • Hidden dependencies. A mixin that calls this.save() silently requires the base class to have save. The requirement lives only in the mixin's body.
  • Harder debugging. Anonymous classes show up as blank names in stack traces and devtools, and you cannot tell which mixin added a method without reading them all.

Composition is the usual alternative: instead of an invoice that is timestamped, write an invoice that has a clock (and a serializer, and a logger), passed in from outside.

class Invoice {
  constructor(id, { clock, logger }) {
    this.id = id;
    this.clock = clock;
    this.logger = logger;
    this.createdAt = clock.now();
  }
}
 
// In production
new Invoice("inv_1", { clock: { now: () => new Date() }, logger: console });
 
// In a test: no mocking library needed
new Invoice("inv_2", { clock: { now: () => new Date("2000-01-01") }, logger: { info() {} } });

Each collaborator is a plain object with a small interface, it can be swapped in tests, and there are no name clashes because each lives under its own property. This is "favour composition over inheritance" made concrete, and it is how most Node services wire things up (often with a dependency-injection container doing the passing for you).

Mixins are not banned. TypeScript documents a mixin pattern, Lit and some UI libraries use them for shared element behaviour, and they suit small, independent capabilities that never call each other. As a rule: use extends for a real "is a" relationship one level deep (custom errors), composition for collaborators, and a mixin only when you have measured that the other two are worse.

Put it in order5 steps

For class Invoice extends Serializable(Timestamped(Model)) {}, order the prototype chain of an instance from nearest to farthest.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
ChallengeMedium

Bank account with private balance

Write a class BankAccount:

  • new BankAccount(owner, initial = 0) stores owner as a public property and the balance in a private field #balance.
  • balance is a getter (read-only from outside).
  • deposit(amount) adds money and returns the new balance. Throw an Error with message "Amount must be positive" if amount <= 0.
  • withdraw(amount) removes money and returns the new balance. Same positive check, and throw "Insufficient funds" if it would go below zero.
  • transfer(to, amount) moves money to another account. If the withdraw fails, nothing changes on either side.
const a = new BankAccount("Ada", 100);
const b = new BankAccount("Sam");
a.transfer(b, 30);
a.balance; // 70
b.balance; // 30
JavaScript
class BankAccount { // Add a #balance private field, a balance getter, and the methods. constructor(owner, initial = 0) { this.owner = owner; }}
ChallengeEasy

Shapes with inheritance

The Shape base class is written for you. Add three subclasses:

  • Circle(radius): name "circle", area π · r²
  • Rectangle(width, height): name "rectangle", area width · height
  • Square(side): extends Rectangle, name "square"

Each must call super(...) and override area(), except Square, which should reuse Rectangle's area. Do not redefine describe: the inherited one must work for all of them.

new Circle(1).describe();       // "circle: 3.14"
new Rectangle(2, 3).describe(); // "rectangle: 6.00"
new Square(4).describe();       // "square: 16.00"
JavaScript
class Shape { constructor(name) { this.name = name; } area() { return 0; } describe() { return this.name + ": " + this.area().toFixed(2); }} // Write Circle, Rectangle and Square below.class Circle extends Shape {}class Rectangle extends Shape {}class Square extends Rectangle {}
Key terms
constructor
The method that runs when you call new. In a subclass it must call super() before using this.
private field (#)
A #name property that only code inside the class body can access, enforced by the language.
static
A member that belongs to the class itself, like Array.from or Promise.all, not to instances.
getter / setter
get x() and set x(v): functions that run when a property is read or assigned.
prototype
The object another object links to. Missing properties are looked up there.
prototype chain
The series of prototype links the engine walks to find a property, ending at null.
shadowing
An own property hiding a property of the same name further up the prototype chain.
realm
A separate JavaScript global environment (window, iframe, worker) with its own copies of the built-ins.
mixin
A function that takes a class and returns a subclass with extra behaviour, inserted into the chain.