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.
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.
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.
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.
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()).
w.#balance = 1000?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.
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:
Press Run (⌘ Enter) to see what happens.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());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 instance holds only its own data: name and radius. No methods are copied into it.
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.
Circle instances. How many copies of the area method exist in memory?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.
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 onobj. It does not walk up and change the prototype. Settingbird.legsgavebirdits ownlegsthat shadows the inherited one, anddogstill sees4.
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).
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{}inheritsconstructor,toStringand friends, so"constructor" in countsis 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 aMapavoids those collisions. It also helps against prototype pollution, an attack where input like{"__proto__": {"isAdmin": true}}is merged into an object and ends up modifyingObject.prototypefor the whole app.- Explicit prototypes in tests and old code. Before
class, inheritance wasChild.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.
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);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:
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.
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 newerError.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
codeornamefield (err.code === "ERR_NOT_FOUND"), or a type guard that checks the properties you need. Node's own errors are designed to be checked bycode, 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.
iframe.contentWindow.items). Which check returns true?When to skip classes
Classes are one tool, not the default. Modern JavaScript, and React in particular, leans toward plain objects and functions:
| Reach for | When |
|---|---|
Plain object { ... } | Data with no behaviour: API responses, config, props, state |
| Functions + closures | Behaviour with a little private state: makeCounter, createStore |
| A class | Many 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.
Order what happens when you run new Circle(2) where Circle extends Shape.
- Tap the steps below in the right order.
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:
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
toJSONorsave, the outer one wins and the inner one is shadowed. Nothing warns you. - Order matters.
Serializable(Timestamped(Model))andTimestamped(Serializable(Model))build different chains, andsuper.method()calls go to different places. - Hidden dependencies. A mixin that calls
this.save()silently requires the base class to havesave. 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.
For class Invoice extends Serializable(Timestamped(Model)) {}, order the prototype chain of an instance from nearest to farthest.
- Tap the steps below in the right order.
Bank account with private balance
Write a class BankAccount:
new BankAccount(owner, initial = 0)storesowneras a public property and the balance in a private field#balance.balanceis a getter (read-only from outside).deposit(amount)adds money and returns the new balance. Throw anErrorwith message"Amount must be positive"ifamount <= 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; // 30Shapes with inheritance
The Shape base class is written for you. Add three subclasses:
Circle(radius): name"circle", areaπ · r²Rectangle(width, height): name"rectangle", areawidth · heightSquare(side): extendsRectangle, 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"- constructor
- The method that runs when you call
new. In a subclass it must callsuper()before usingthis. - private field (#)
- A
#nameproperty that only code inside the class body can access, enforced by the language. - static
- A member that belongs to the class itself, like
Array.fromorPromise.all, not to instances. - getter / setter
get x()andset 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.