JS-102 · Lesson 6 of 12 · 27 min
Prototypes and classes
▶ Video coming soon A video version of this lesson is on the way.
By the session planned for Thursday, December 3, the holiday hamper drive is close, and Mira has a new kind of record to model. Each hamper is packed for one household, has a size (small, family or large), a list of items and a status that moves from packing to packed to picked up. There will be about three hundred of them. Writing three hundred object literals, each with its own copy of the same methods, is clearly wrong. Mira's factory function from Lesson 1 would work, but Gareth wants her to see the way JavaScript itself shares behaviour between objects, and the class syntax most teams use for it.
"Classes in JavaScript are a nicer way of writing something the language has always done with prototypes," he says. "If you understand the prototype chain, classes stop being mysterious. And when something goes wrong with a class, it is the prototype chain you end up debugging." So the lesson starts underneath, with prototypes, and then builds up to classes, private fields, static members and inheritance.
The prototype chain
Every JavaScript object has a hidden link to another object, called its prototype. When you read a property that the object does not have itself, the engine follows the link and looks in the prototype; if it is not there either, it follows the prototype's own link, and so on. This series of links is the prototype chain. It ends at Object.prototype, whose own prototype is null. Assigning a property always creates or changes it on the object itself, never on the prototype.
The prototype chain is why every object has methods such as toString and hasOwnProperty without your writing them, and why every array has map and filter: arrays are linked to Array.prototype, which holds those methods. You can see the link with Object.getPrototypeOf, and create an object with a chosen prototype using Object.create.
const hamperMethods = {
describe() {
return `${this.size} hamper for ${this.family}`;
},
};
const h1 = Object.create(hamperMethods);
h1.family = 'Okafor';
h1.size = 'Family';
const h2 = Object.create(hamperMethods);
h2.family = 'Lindgren';
h2.size = 'Small';
console.log(h1.describe());
console.log(h2.describe());
console.log(Object.hasOwn(h1, 'describe'), h1.describe === h2.describe);
console.log(Object.getPrototypeOf(h1) === hamperMethods);Family hamper for Okafor Small hamper for Lindgren false true true
What this code does
Object.create makes two new objects whose prototype is hamperMethods, and each gets its own family and size. Neither object has a describe property of its own, so the engine finds it one step up the chain, in hamperMethods. Both hampers therefore share a single describe function, and this inside it refers to whichever hamper it was called on.
This is the key idea: data lives on each object, behaviour lives once on the shared prototype. Three hundred hampers need three hundred sets of family, size and items, but only one describe function. Before 2015, JavaScript developers built this pattern with constructor functions, ordinary functions called with the keyword new, which creates an object, links it to the function's prototype property and runs the function with this set to the new object. Classes now do the same thing with clearer syntax.
// The older constructor-function pattern, shown for recognition
function Hamper(family, size) {
this.family = family;
this.size = size;
}
Hamper.prototype.describe = function () {
return `${this.size} hamper for ${this.family}`;
};
const h = new Hamper('Okafor', 'Family');Class syntax
A class is a template for creating objects that share the same structure and methods. You declare it with the keyword class and a name, which by convention starts with a capital letter. Inside the class body, a special method called constructor runs when a new object is created and usually stores the starting data on this. Other methods written in the body are placed on the class's prototype, so all objects made from the class share them. An object made from a class is called an instance of it, and you create one with new.
class Hamper {
constructor(family, size) {
this.family = family;
this.size = size;
this.items = [];
this.status = 'packing';
}
add(item) {
this.items.push(item);
return this;
}
describe() {
return `${this.size} hamper for ${this.family}: ${this.items.length} items, ${this.status}`;
}
}
const okafor = new Hamper('Okafor', 'Family');
okafor.add('rice').add('beans').add('oats');
const lindgren = new Hamper('Lindgren', 'Small');
console.log(okafor.describe());
console.log(lindgren.describe());
console.log(okafor);
console.log(okafor instanceof Hamper, typeof Hamper);Family hamper for Okafor: 3 items, packing
Small hamper for Lindgren: 0 items, packing
Hamper { family: "Okafor", size: "Family", items: [ "rice", "beans", "oats" ], status: "packing" }
true functionWhat this code does
new Hamper creates an object, runs the constructor with this set to it and returns it, so each hamper gets its own family, size, items and status. Because add returns this, calls can be chained, adding three items to the Okafor hamper. The printed object is labelled with the class name, instanceof confirms where it came from, and typeof shows that a class is really a function.
A few details make classes safer than the older pattern. A class must be called with new; calling Hamper('Okafor') without it throws a TypeError instead of quietly misbehaving. The code inside a class body always runs in strict mode. And class declarations are hoisted like let, into a temporal dead zone, so you must declare a class before you use it.
Underneath, nothing new has happened. Object.getPrototypeOf(okafor) === Hamper.prototype is true, and describe lives on Hamper.prototype, exactly as in the constructor-function version. This is why people say classes are syntactic sugar over prototypes: a sweeter way to write the same thing.
Class fields
Properties that every instance starts with can be declared directly in the class body as class fields, instead of being assigned in the constructor. A field is written as a name, optionally followed by an equals sign and a starting value. Fields make the shape of an instance visible at a glance and leave the constructor for values that come from arguments.
class Shift {
program;
crew = [];
capacity = 6;
constructor(program, capacity) {
this.program = program;
if (capacity !== undefined) this.capacity = capacity;
}
join(name) {
if (this.crew.length >= this.capacity) return false;
this.crew.push(name);
return true;
}
}
const kitchen = new Shift('Kitchen', 2);
console.log(kitchen.join('Priya'), kitchen.join('Jonah'), kitchen.join('Amara'));
console.log(kitchen);
console.log(new Shift('Pantry').capacity);true true false
Shift { program: "Kitchen", crew: [ "Priya", "Jonah" ], capacity: 2 }
6What this code does
The fields declare that every shift has a program, a crew array of its own and a capacity of 6 unless told otherwise. The kitchen shift is given a capacity of 2, so the third volunteer is refused. A pantry shift created without a capacity keeps the field's default of 6.
Each instance gets its own copy of every field, so crew = [] gives every shift a separate empty array, which is exactly what you want. If you put an array on the prototype instead, all instances would share it, which is a classic bug. Fields are initialized before the constructor body runs, so the constructor can rely on them.
Private fields and methods
Lesson 1 used closures to keep a sign-up list private. Classes have a direct way to do the same. A field or method whose name starts with # is private: it can be used only by code inside the class body. Code outside cannot read it, change it or even check whether it exists in the ordinary way; trying to write okafor.#items outside the class is a SyntaxError. Private members became part of the language in ES2022.
class DonationLog {
#entries = [];
add(donor, boxes) {
if (!Number.isInteger(boxes) || boxes <= 0) {
return `Rejected ${boxes} boxes from ${donor}`;
}
this.#entries.push({ donor, boxes });
return `Logged ${boxes} boxes from ${donor}`;
}
get total() {
return this.#entries.reduce((sum, e) => sum + e.boxes, 0);
}
#countFrom(donor) {
return this.#entries.filter((e) => e.donor === donor).length;
}
summary(donor) {
return `${donor}: ${this.#countFrom(donor)} donations`;
}
}
const log = new DonationLog();
console.log(log.add('Lakeside Grocers', 12));
console.log(log.add('St. Mark School', -3));
console.log(log.add('Lakeside Grocers', 9));
console.log(log.total, log.summary('Lakeside Grocers'));
console.log(log, Object.keys(log));Logged 12 boxes from Lakeside Grocers
Rejected -3 boxes from St. Mark School
Logged 9 boxes from Lakeside Grocers
21 Lakeside Grocers: 2 donations
DonationLog {} []What this code does
The array of entries is private, so the only way to add to it is through add, which rejects anything that is not a positive whole number of boxes. The getter total and the method summary work on the private data from inside the class. When the log itself is printed, the private field does not show and Object.keys finds no properties at all.
Private fields are a stronger guarantee than the underscore convention, such as _entries, that older code uses to mean "please don't touch". An underscore is only a polite request; a # is enforced by the engine. Use private fields for anything whose rules must hold, such as Lucy's capacity check or the rejection of impossible donations, and expose only methods and getters that keep those rules.
Static members
A static method or field belongs to the class itself, not to its instances. You call it on the class name, as in Hamper.fromRecord(data), and inside it this refers to the class. Static methods are commonly used for factory methods, which create instances in a particular way, and for helpers that relate to the class but do not need an instance. Static fields hold values shared by the whole class, such as a list of allowed sizes.
class Hamper {
static SIZES = ['Small', 'Family', 'Large'];
static #nextId = 1;
constructor(family, size) {
if (!Hamper.SIZES.includes(size)) throw new RangeError(`Unknown size: ${size}`);
this.id = Hamper.#nextId++;
this.family = family;
this.size = size;
}
static fromRecord(record) {
return new Hamper(record.family.trim(), record.size);
}
}
const a = new Hamper('Okafor', 'Family');
const b = Hamper.fromRecord({ family: ' Lindgren ', size: 'Small' });
console.log(a, b);
console.log(Hamper.SIZES.length, typeof a.fromRecord);
try {
new Hamper('Nguyen', 'Huge');
} catch (err) {
console.log(err.name, err.message);
}Hamper { id: 1, family: "Okafor", size: "Family" } Hamper { id: 2, family: "Lindgren", size: "Small" }
3 undefined
RangeError Unknown size: HugeWhat this code does
The static list of sizes and the private static counter belong to the class, so every new hamper takes the next ID number from the same counter. fromRecord is a static factory that tidies a record before creating a hamper, and it is called on Hamper itself, which is why the instance a has no fromRecord method. The constructor refuses an unknown size by throwing a RangeError, which the try and catch block reports.
Throwing an error from a constructor is the standard way to refuse to create an invalid object. Lesson 8 covers errors fully; for now, notice that validation in the constructor means no code anywhere can create a hamper of an impossible size, which is much easier to trust than checks scattered through the program.
Inheritance with extends and super
A class can be based on another class with extends. The new class, called a subclass or child class, inherits all the methods of the superclass or parent class and can add methods of its own or replace inherited ones. In the subclass's constructor, you must call super(...) before using this; it runs the parent's constructor to set up the inherited part of the object. Inside a method, super.methodName() calls the parent's version of a method.
class Shift {
constructor(program, start) {
this.program = program;
this.start = start;
}
describe() {
return `${this.program} shift at ${this.start}`;
}
}
class KitchenShift extends Shift {
constructor(start, menu) {
super('Kitchen', start);
this.menu = menu;
}
describe() {
return `${super.describe()}, serving ${this.menu}`;
}
}
const pantry = new Shift('Pantry', '9:00');
const lunch = new KitchenShift('11:00', 'squash soup');
console.log(pantry.describe());
console.log(lunch.describe());
console.log(lunch instanceof KitchenShift, lunch instanceof Shift);Pantry shift at 9:00 Kitchen shift at 11:00, serving squash soup true true
What this code does
KitchenShift extends Shift, so its constructor first calls super with the program name and start time, letting the parent set those properties. Its own describe replaces the parent's but still calls super.describe() and adds the menu to the end. A kitchen shift counts as an instance of both classes, because Shift's prototype is further up its chain.
Replacing an inherited method with a new version is called overriding. Look at what the chain does: when lunch.describe() runs, the engine finds describe on KitchenShift.prototype first and stops there. A method that the subclass does not override, such as one Shift might add later, would be found one level further up. Built-in classes can be extended too; class ValidationError extends Error is a common example you will meet in Lesson 8.
| Feature | Syntax | Belongs to | Visible outside the class? |
|---|---|---|---|
| Constructor | constructor(a, b) { ... } | Runs once per new instance | Called through new |
| Method | describe() { ... } | The prototype, shared by instances | Yes |
| Public field | crew = []; | Each instance | Yes |
| Private field or method | #entries = []; | Each instance | No |
| Getter or setter | get total() { ... } | The prototype | Yes, used like a property |
| Static method or field | static fromRecord() { ... } | The class itself | Yes, through the class name |
| Inheritance | class B extends A | Links B.prototype to A.prototype | Yes |
When to use a class
Classes are not the only way to organize objects, and Gareth is careful not to oversell them. A class is a good fit when you will create many objects with the same structure and behaviour, when instances need to protect rules about their own data, or when a library or framework expects classes. Hampers, shifts and donation logs all qualify. A plain object is better for a single collection of settings, such as the Food Hub's rules. Plain functions that take and return data, like the map and reduce pipelines from Lesson 3, are often simpler still for calculations.
Inheritance in particular should be used sparingly. A subclass is tightly tied to its parent, and long chains, such as Shift, then KitchenShift, then HolidayKitchenShift, become hard to change. Many experienced developers follow the guideline "prefer composition over inheritance": instead of making a class that is a special kind of another class, give it a property that holds a helper object, or pass the varying behaviour in as a function. One level of extends is common and fine; three is a warning sign.
Worked problem
Designing the Hamper class
Lucy needs hampers that record a family name and a size, collect items, report how many items they hold and refuse to be marked picked up before they are packed. Sketch the class.
Show solution
- Data each instance needs: family and size, given to the constructor; items, starting as an empty array; status, starting as 'packing'. items and status can be fields.
- The status has rules, so make it private: #status = 'packing', with a getter status that returns it, so outside code can read but not set it directly.
- Behaviour: add(item) pushes to items; a getter count returns items.length; markPacked() sets #status to 'packed'.
- pickUp() checks the rule: if #status is not 'packed', throw an Error saying the hamper is not packed yet; otherwise set it to 'picked up'.
- Validation: in the constructor, refuse a size that is not in a static SIZES list.
Answer: A class Hamper with fields items and #status, a constructor that validates size, methods add, markPacked and pickUp, getters count and status, and a static SIZES list. The private status means the packing rule cannot be skipped.
Try it yourself
A hamper class
Write a class Hamper whose constructor takes family and size and stores them. Each hamper also starts with its own empty items array.
Add a method add(...newItems) that adds any number of items, a getter count that returns the number of items, and a method label() that returns text such as Okafor (Family): 3 items.
class Hamper {
constructor(family, size) {
// store family and size; give the hamper an empty items array
}
add(...newItems) {
// add the new items
}
get count() {
return 0; // replace with the number of items
}
label() {
return ''; // replace with the label text
}
}
const h = new Hamper('Okafor', 'Family');
h.add('rice', 'beans');
h.add('oats');
console.log(h.count);
console.log(h.label());
console.log(new Hamper('Lindgren', 'Small').label());Try it yourself
A subclass for holiday shifts
The starter has a Shift class. Write a subclass HolidayShift that extends it. Its constructor takes program, start and bonus, passes the first two to super, and stores bonus.
Override describe() so that it returns the parent's description followed by (holiday: and the bonus, then ). Use super.describe().
class Shift {
constructor(program, start) {
this.program = program;
this.start = start;
}
describe() {
return `${this.program} at ${this.start}`;
}
}
class HolidayShift extends Shift {
// add a constructor that calls super, and override describe
}
const s = new HolidayShift('Hamper packing', '10:00', 'hot chocolate');
console.log(s.describe());
console.log(s instanceof Shift);Common mistakes
MistakeEvery instance gets its own copy of each method.
InsteadMethods live once on the class's prototype and are shared; only fields and constructor assignments are per instance.
MistakeA subclass constructor can use this before calling super.
InsteadIt must call super(...) first; using this before that throws a ReferenceError.
MistakeA name starting with an underscore is private.
InsteadAn underscore is only a convention. Only names starting with # are enforced as private.
MistakeStatic methods can be called on instances.
InsteadStatic members belong to the class, so call them as ClassName.method().
MistakeClasses are a completely separate system from prototypes.
InsteadClasses are built on the prototype chain; class methods are stored on ClassName.prototype.
Summary and key terms
- Every object has a prototype, and property lookups follow the prototype chain until they find the property or reach null.
- Shared behaviour lives on the prototype, while data lives on each object.
- Object.create makes an object with a chosen prototype.
- A class is a template whose constructor sets up each new instance and whose methods are shared through the prototype; instances are made with new.
- Class fields declare per-instance properties, and names starting with # are private and enforced by the engine.
- Static members belong to the class itself and suit factory methods and shared constants. extends creates a subclass, super(...) runs the parent constructor and super.method() calls the parent's version of an overridden method.
- Use classes for many similar objects with rules to protect, and prefer composition to deep inheritance.
- prototype
- The object that another object is linked to and from which it inherits properties.
- prototype chain
- The series of prototype links followed when a property is looked up.
- class
- A template for creating objects with the same structure and shared methods.
- constructor
- The special method of a class that runs when a new instance is created.
- instance
- An object created from a class with new.
- class field
- A property declared in a class body that every instance receives.
- private field
- A class member whose name starts with # and which only code inside the class can use.
- static member
- A method or field that belongs to the class itself rather than to its instances.
- subclass
- A class created with extends that inherits from another class.
- super
- A keyword that calls the parent class's constructor or methods from a subclass.
- overriding
- Replacing an inherited method with a new version in a subclass.
- syntactic sugar
- Syntax that makes something easier to write without adding a new ability.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Where is a method declared in a class body stored?
Show answer
On the class's prototype, ClassName.prototype, shared by every instance.
What does new do when it calls a class?
Show answer
Creates an object linked to the class's prototype, runs the constructor with this set to it and returns it.
Why is crew = [] as a class field safe, while an array on the prototype is not?
Show answer
Each instance gets its own array from the field; an array on the prototype would be shared by all instances.
How would you call the parent's describe method from inside an overriding describe?
Show answer
super.describe().
Can code outside a class read a private field such as #entries?
Show answer
No. Mentioning it outside the class body is a SyntaxError.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.