JavaScript Prototypes and Classes Explained
On this page
Learning Objective
Explain the prototype chain and how property lookup walks it, relate class syntax to the prototypes it creates, use inheritance, static members and true private fields, and know when composition and plain objects are a better fit than class hierarchies in frontend code.
Concept Explanation
JavaScript objects can delegate to other objects. Every object has an internal link to a prototype, another object or null. When you read a property, the engine looks on the object itself first, then on its prototype, then on the prototype's prototype, until it finds the property or reaches null. This is the prototype chain. Writing a property, by contrast, creates it on the object itself, shadowing any property with the same name further up the chain. Object.getPrototypeOf reads the link, Object.create makes an object with a chosen prototype, and Object.hasOwn tells you whether a property is the object's own.
Built-in behavior works the same way. An array literal's prototype is Array.prototype, which provides map, filter and push, and Array.prototype's prototype is Object.prototype, which provides toString and hasOwnProperty. Methods are shared through the prototype rather than copied into each object, which saves memory. That is also why modifying built-in prototypes, monkey patching, is dangerous: every array or object in the program, including those of your dependencies, sees the change.
The class syntax introduced in 2015 is a clearer way to set up the same machinery. A class's constructor runs when you call new, methods in the class body are placed on the prototype, and extends links one class's prototype to another's so lookups continue up the hierarchy. super calls the parent constructor or a parent method. Classes add a few things beyond syntax: class bodies are always strict, classes cannot be called without new, and their declarations sit in the temporal dead zone like let.
Modern classes also support fields declared in the body, static members that belong to the class itself, such as factory methods, and true private members with the hash prefix. A private field such as #balance can only be accessed inside the class body; it does not appear in Object.keys, JSON.stringify or the console's normal property list, and access from outside is a syntax error. This is real encapsulation, unlike the old convention of an underscore prefix. Getters and setters let a class expose computed or validated properties.
In frontend code, deep class hierarchies are rarely the right tool. UI frameworks have moved toward functions and composition: React components are functions, and shared behavior lives in hooks rather than base classes. Plain objects and functions are easier to serialize, test and tree shake. Classes still shine for objects with identity, internal state and a clear lifecycle, such as an API client, a WebSocket connection manager, a custom element (Day 20) or a custom Error subclass that carries extra information.
| Concept | Syntax | Note |
|---|---|---|
| Prototype lookup | obj.prop walks the chain | Writes create own properties |
| Create with a prototype | Object.create(proto) | Delegation without classes |
| Own property check | Object.hasOwn(obj, 'x') | Ignores the prototype chain |
| Class methods | method() in the class body | Shared on the prototype |
| Inheritance | class B extends A, super() | Links prototypes |
| Static member | static fromJSON() | On the class, not instances |
| Private field | #balance | Inaccessible outside the class body |
| Composition | Functions and objects combined | Preferred over deep hierarchies |
Worked Example: An API Client and a Custom Error Class
The client keeps private configuration, exposes a static factory and throws a custom error with structured details. The final lines inspect the prototype chain.
class ApiError extends Error {
constructor(status, problem) {
super(problem?.title ?? `Request failed with ${status}`);
this.name = 'ApiError';
this.status = status;
this.fieldErrors = problem?.errors ?? {};
}
get isAuth() { return this.status === 401 || this.status === 403; }
}
class ApiClient {
#baseUrl; // truly private
#fetch;
static #instances = 0;
constructor(baseUrl, fetchImpl = fetch) {
this.#baseUrl = baseUrl.replace(/\/$/, '');
this.#fetch = fetchImpl;
ApiClient.#instances++;
}
static fromEnv() { return new ApiClient(import.meta.env.VITE_API_URL); }
static get instanceCount() { return ApiClient.#instances; }
async get(path, { signal } = {}) {
const res = await this.#fetch(`${this.#baseUrl}${path}`, { credentials: 'include', signal });
if (!res.ok) {
const problem = res.headers.get('content-type')?.includes('json') ? await res.json() : null;
throw new ApiError(res.status, problem);
}
return res.json();
}
}
const api = new ApiClient('https://api.example.com/');
try {
await api.get('/v1/orders');
} catch (e) {
if (e instanceof ApiError && e.isAuth) redirectToLogin();
}
// Inspecting the chain
console.log(Object.getPrototypeOf(api) === ApiClient.prototype); // true
console.log(Object.hasOwn(api, 'get')); // false: on the prototype
console.log(Object.keys(api), JSON.stringify(api)); // [] '{}': private fields hidden
// api.#baseUrl; // SyntaxError outside the classAccepting fetchImpl in the constructor is a small dependency injection that makes the client easy to test with a fake fetch, which matters more in practice than any inheritance hierarchy.
Real-World Examples
- Private class fields and methods with the hash syntax became part of ECMAScript 2022, and TypeScript, which had long offered compile-time private modifiers, added support for the runtime-enforced hash syntax so that privacy holds even in emitted JavaScript.
- MooTools, a popular library in the late 2000s, extended built-in prototypes such as Array.prototype, and its flatten and contains methods forced the TC39 committee to rename proposed standard methods to flat and includes to avoid breaking websites, an episode often called "SmooshGate".
Review Questions & Answers
Reading finds it by walking up the prototype chain and returns the prototype's value. Writing creates a new own property on the object itself, shadowing the prototype's property for that object only, without changing the prototype.
Underscore properties are ordinary public properties that anyone can read and change; the underscore is only a convention. Hash fields are enforced by the language: they cannot be accessed outside the class body, and they do not appear in Object.keys, JSON serialization or for loops over properties.
Every object of that type in the whole program, including code in dependencies, sees the change, which can break other code, conflict with other libraries and even block the language from adding standard methods with the same name, as happened with flatten and contains.
When an object has identity, internal state and a lifecycle, such as an API client with configuration, a connection manager, a custom element, or a custom Error subclass. For shared UI behavior, functions, hooks and composition are usually simpler.