T5 Modern JavaScript (ES6 and later) · Lesson 5
Classes
Making many objects of one kind from one pattern: a class with its constructor and methods, fields and private fields, getters and setters that check what they are given, static methods and fields that belong to the class, inheritance with extends and super, and error classes of your own with a name of their own.
- write a class with a constructor and methods, and make objects from it with new
- give a class public fields, and private fields and methods that no outside code can reach
- write getters for values worked out on the spot, and setters that refuse bad values
- use static methods and fields for what belongs to the class, not to each object
- extend a class, call super in its constructor and methods, and test objects with instanceof
- make an error class that extends Error, with its own name, and catch it by its kind
The back cover
A school keeps a record for every student, and every record has the same boxes: name, roll number and marks. The same few things can be done with each one. A class is that pattern written once, so that any number of objects can be made from it.
These pages show a class with its constructor and methods, and fields that are public or private. They show getters and setters that check what they are given, and static members that belong to the class itself. They show one class built on another, and error classes of your own.
Before you start
The story: Forty clocks by hand
Every clock on the upper floor has a record in the Script: its name, its chime, and how many times it has been wound. Each record was written out by hand, as an object, by whoever put the clock up. The east clock's record spells chime as chmie, so the east clock has never chimed at all.
And last week somebody set the west clock's winding count to minus three, which no clock can ever have been wound.
Master Hakim Verge runs a finger down the forty records. "Forty clocks, forty records written by hand, forty chances to slip," he says. "No clockmaker carves each clock from nothing. Every clock of a kind comes from one pattern. Write the pattern."
A program often needs many objects of one kind: forty clocks, a thousand tickets, every account of a bank. The objects lesson made them with a factory function. Modern JavaScript has a dedicated way to write such a pattern, the class. It keeps the pattern's data and behaviour together, can hide what must not be touched, and lets one pattern extend another.
It builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| Objects and properties. | { from: "Pune", fare: 350 } | Every object a class makes. |
| Methods and this. | count() { return this.items.length; } | A class's methods. |
| Factory functions. | makeStudent(name, roll) | A class does the same job. |
| Getters and setters. | get rupees() { ... } | In a class, over a private field. |
| Closures for private data. | A wallet's balance inside makeWallet. | Private fields do it more plainly. |
| Arrows have no this of their own. | And cannot be called with new. | Arrow fields that keep this. |
| Error objects. | err.name and err.message | Error classes of your own. |
| instanceof. | err instanceof TypeError | Asking which class made an object. |
| RangeError. | A number outside what is allowed. | Setters and methods that refuse bad values. |
| Modules. | export function withGst | A class is often a module's export. |
By the end of this lesson you will be able to:
- write a class with a constructor and methods, and make objects from it with new;
- give a class public fields, and private fields and methods that no outside code can reach;
- write getters for values worked out on the spot, and setters that refuse bad values;
- use static methods and fields for what belongs to the class, not to each object;
- extend a class, call super in its constructor and methods, and test objects with instanceof;
- make an error class that extends Error, with its own name, and catch it by its kind.
How to follow this lesson
Think of a class as a mould and its objects as what comes out of it. Each time a block makes an object with new, ask: what does this object hold of its own, and what does it share with every other object from the same mould?
In one line
A class is a pattern for many objects of one kind, with their data, their methods and what they keep private; this lesson builds one up, piece by piece.
A class and its objects
At a glance
A mould for a clay lamp makes a hundred lamps of one shape; each can be painted differently, but the shape comes from the mould. A class is a mould for objects.
Its constructor sets up each new object with this, and its methods are shared by every object it makes. The word new makes an object from the class, and instanceof asks whether a class made a given object. A class must be called with new: called like a plain function, it throws a TypeError.
Take a guess: Can an array made in one frame of a page fail instanceof Array in another?
A railway sells thousands of tickets. Each ticket has a starting station, a destination and a fare, and each can describe itself. Here is the pattern for all of them, written as a class:
class Ticket {
constructor(from, to, fare) {
this.from = from;
this.to = to;
this.fare = fare;
}
describe() {
return `${this.from} to ${this.to}: ₹${this.fare}`;
}
}
const t = new Ticket("Pune", "Mumbai", 350);
console.log(t.describe(), typeof Ticket, t instanceof Ticket);
Pune to Mumbai: ₹350 function true
Take it one piece at a time. class Ticket { ... } declares the pattern and names it, with a capital letter by custom. Inside the braces, the class lists what every ticket gets.
The method named constructor inside a class. It runs once for each new object, with the arguments given to new, and its job is to set up the object, usually by giving it properties with this.name = value.
new Ticket("Pune", "Mumbai", 350) makes a fresh empty object, runs the constructor with this pointing at that object, and gives the object back. An object made from a class is called an instance of it. Then describe is a method, written as in an object literal, and every ticket can call it.
typeof shows that a class is a special kind of function, and instanceof, met in the errors lesson, asks whether an object was made by a class. t was made by Ticket, so it is true.
new is not optional
A class can only be used with new. Called like an ordinary function, it refuses:
class Ticket {}
Ticket();
Uncaught TypeError: Class constructor Ticket cannot be invoked without 'new'
at line 2
What each object owns, and what they share
Each ticket has its own from, to and fare, set by its own run of the constructor. The methods are different: they are stored once, on the class, and every instance uses the same one. That is why a thousand tickets do not mean a thousand copies of describe:
class Ticket {
constructor(fare) {
this.fare = fare;
}
describe() {
return `₹${this.fare}`;
}
}
const a = new Ticket(100);
const b = new Ticket(200);
console.log(a.fare, b.fare, a.describe === b.describe, a.describe(), b.describe());
100 200 true ₹100 ₹200
One describe, shared, and still each answer is the ticket's own, because this is the ticket the method is called on. Printing an instance shows its class's name and its own properties only:
class Item {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
console.log(new Item("tea", 15));
Item { name: 'tea', price: 15 }
| Factory function | Class | |
|---|---|---|
| written | function makeTicket(fare) { return { ... }; } | class Ticket { constructor(fare) { ... } } |
| used | makeTicket(100) | new Ticket(100) |
| methods | a new copy in every object | one copy, shared by all instances |
| which made this object? | not recorded | t instanceof Ticket |
| private data | a closure | private fields, in the next section |
Unlike a function declaration, a class cannot be used above the line that declares it. Declare classes before you use them, usually at the top of a file or in a module of their own.
Worked example 1
A school library lends books. Each loan has a book title, a student and the number of days. Write a class Loan with a method dueIn() that says how many days are left after a given number of days have passed, and make two loans.
What we have: a title, a student and a number of days for each loan
What we need: two loans that each answer for themselves
The plan: a constructor that stores the three values, and a method that subtracts the days passed from the loan's days
class Loan {
constructor(title, student, days) {
this.title = title;
this.student = student;
this.days = days;
}
dueIn(passed) {
return `${this.title}: ${this.days - passed} days left for ${this.student}`;
}
}
const first = new Loan("Panchatantra", "Meera", 14);
const second = new Loan("Wings of Fire", "Kabir", 7);
console.log(first.dueIn(10));
console.log(second.dueIn(3));
Panchatantra: 4 days left for Meera
Wings of Fire: 4 days left for Kabir
Both loans have 4 days left, each worked out from its own days.
Check: 14 − 10 = 4 and 7 − 3 = 4, and each line names its own book and student.
A path that fails: writing each loan by hand as an object literal with its own dueIn. It works for two loans, and a library has thousands; a slip in one copy, such as a misspelt property, breaks only that loan, where nobody looks.
When you are stuck: an object made from a class misbehaves
Did you call it with new? Without new, a class refuses with a TypeError.
Check the constructor: each property the methods use must be set there with this.
Print the instance: it shows the class name and its own properties.
Use instanceof to ask which class made an object.
Your turn
class Box {
constructor(size) {
this.size = size;
}
double() {
return this.size * 2;
}
}
const small = new Box(3);
const big = new Box(10);
console.log(small.double(), big.double(), small.double === big.double);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
6 20 true
- Each box has its own size: 3 and 10.
- double is one shared method, so the comparison is true.
It prints 6 20 true.
What does new do, in three steps?Tap to reveal
- It makes a fresh empty object.
- It runs the constructor with this pointing at that object.
- It gives the object back.
It makes the object, runs the constructor on it, and returns it.
Why is Ticket(), without new, an error?Tap to reveal
- A class can only be used with new.
Because a class constructor cannot be invoked without new: a TypeError.
Did you know?
Called without new
A class refuses to be called like a plain function. MDN explains that all class constructors must be called with new, and that calling one without it throws a TypeError. The standard's steps create that TypeError the moment a class constructor is called. Older constructor functions had no such guard: JavaScript functions were used both as constructors and as normal functions.
Why it fits here: It explains this topic's rule about new: a class cannot be called without it, so the slip is caught at once.
Sources: MDN: TypeError: class constructors must be invoked with 'new'; ECMAScript Language Specification: [[Call]] of ECMAScript function objects
instanceof and frames
instanceof does not ask about a class's name: it looks for the class's prototype along the object's prototype chain. MDN shows the surprise this causes. Each window or frame has its own built-ins, so an array made in the page fails instanceof the Array of a frame inside it. MDN's answer is Array.isArray, which says whether a value is an array whichever realm it came from.
Why it fits here: It sharpens this topic's instanceof: it compares prototypes, so the same class from another frame does not count.
Sources: MDN: instanceof; ECMAScript Language Specification: OrdinaryHasInstance
In one line
A class is a pattern: its constructor sets up each new object with this, and its methods are shared by every instance. Make objects with new, and ask which class made one with instanceof.
Fields: public and private
At a glance
Every new account at a bank starts with a balance of zero and a list of no transactions. Fields write those starting values once, in the class body, for every object.
A field such as count = 0 gives each instance its own starting value. A name that starts with # is private: only the class's own code can use it, and to everything else it does not exist. Code outside cannot read it, change it, or even see that it is there.
Take a guess: Why do private names in JavaScript start with #, and not with a word like private?
A property that every instance starts with can be written in the class body itself, without a constructor. It is called a field:
class Counter {
count = 0;
add() {
this.count++;
return this.count;
}
}
const c = new Counter();
c.add();
console.log(c.add(), c);
2 Counter { count: 2 }
count = 0; gives every new counter its own count, starting at 0, as if the constructor had written this.count = 0;. Fields make the shape of an instance easy to see at the top of the class.
Private fields
A public field can be changed by any code that holds the object, which is how the west clock's count became minus three. A field whose name starts with # is private: only code written inside the class can read or change it.
A field whose name starts with #, such as #balance. It exists on every instance, but only code inside the class body can use it, as this.#balance. To any other code it does not exist.
class Wallet {
#balance = 0;
deposit(amount) {
this.#balance += amount;
return this.#balance;
}
}
const w = new Wallet();
w.deposit(500);
console.log(w.deposit(200), w.balance, Object.keys(w), w);
700 undefined [] Wallet {}
deposit, inside the class, uses #balance freely: 500, then 700. Outside, the wallet looks empty. w.balance is undefined, because there is no property called balance; Object.keys finds nothing; and printing shows Wallet {}. The # is part of the name, and only the class can say it.
Trying to reach it from outside is not even allowed to run. JavaScript refuses the whole program before its first line:
class Wallet {
#balance = 0;
}
const w = new Wallet();
console.log(w.#balance);
Uncaught SyntaxError: Private field '#balance' must be declared in an enclosing class
This is the same protection as the closure wallet of the scope lesson, written more plainly. The scope lesson's closure kept balance in a function's scope; a private field keeps it in the object, where every method of the class can reach it.
Private methods
A method can be private too, for a helper that only the class's own methods should call. Here a private check guards every deposit:
class Wallet {
#balance = 0;
#check(amount) {
if (amount <= 0) throw new RangeError(`Amount must be more than 0, got ${amount}`);
}
deposit(amount) {
this.#check(amount);
this.#balance += amount;
return this.#balance;
}
}
const w = new Wallet();
w.deposit(-5);
Uncaught RangeError: Amount must be more than 0, got -5
at #check (line 4)
at deposit (line 7)
at line 13
The stack trace shows #check by its private name, called from deposit, called from line 13. The balance was never touched, because the check came first.
| Public field | Private field | |
|---|---|---|
| written | count = 0; | #balance = 0; |
| used inside the class | this.count | this.#balance |
| used outside | c.count, read and changed | a SyntaxError: it cannot be named |
| printed or listed | shown | not shown |
Worked example 2
The Clock Tower's clocks must never have a negative winding count. Write a class Clock with a name, a private #windings that starts at 0, a method wind() that adds one turn, and a method report() that says the name and the count. Wind the west clock three times.
What we have: a clock's name, and windings that only go up
What we need: a count that no outside code can set
The plan: keep windings in a private field, change it only in wind, and read it only in report
class Clock {
#windings = 0;
constructor(name) {
this.name = name;
}
wind() {
this.#windings++;
}
report() {
return `${this.name}: wound ${this.#windings} times`;
}
}
const west = new Clock("West clock");
west.wind();
west.wind();
west.wind();
west.windings = -3;
console.log(west.report());
West clock: wound 3 times
It reports West clock: wound 3 times.
Check: the line west.windings = -3; made a new public property called windings, and left the private #windings alone.
A path that fails: a public field windings = 0;. Then west.windings = -3; changes the real count, which is what happened in the scene.
When you are stuck: a private field gives an error or undefined
Inside the class, write this.#name, with the #; without it you reach a different, public property.
Outside the class, a private field cannot be used at all: add a method that reads it.
A private field must be declared in the class body, #name = ..., before methods use it.
To check whether an object has the field, a class can write #name in obj.
Your turn
class Bag {
#items = 0;
add() {
this.#items++;
return this.#items;
}
}
const bag = new Bag();
bag.add();
bag.items = 50;
console.log(bag.add(), bag.items);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
2 50
- add changes the private #items: 1, then 2.
- bag.items is a separate public property, set to 50.
It prints 2 50.
Why does console.log(w.#balance) outside the class stop the program before it starts?Tap to reveal
- A private name can only be written inside its class's body.
Because it is a SyntaxError: the private field must be declared in an enclosing class.
Write a field that gives every Player a score starting at 0.Tap to reveal
- A field is written in the class body, with its first value.
score = 0;
Did you know?
Why the hash
The # in a private name has a reason. The FAQ of TC39's class fields proposal explains that a private field named x must not stop an object from also having a public field named x, so reading a private field cannot be an ordinary lookup. It adds that this is an issue only because JavaScript lacks static types. Typed languages can tell the two apart; JavaScript lets the name carry the mark.
Why it fits here: It answers this topic's question: a keyword could not tell a private x from a public x at run time, so the name itself is marked.
Asking whether a field is there
A class can ask whether an object has one of its private fields. MDN shows #x in obj, which checks for a private element without the TypeError that reading a missing one would throw. The 2022 edition of the standard has the grammar for it, a private name before in, and TC39's list of finished proposals calls it ergonomic brand checks for private fields.
Why it fits here: It gives this topic's private fields a safe test: #x in obj says whether the field is there, without throwing.
Sources: MDN: in; ECMAScript 2022 Language Specification; TC39: Finished Proposals
In one line
Fields written in the class body give every instance its own starting values. A name that starts with # is private: only the class's own code can use it, and to everything else it does not exist.
Getters and setters
At a glance
A thermostat shows the temperature by reading it fresh each time, and refuses a setting of 500 degrees. Getters and setters let a property behave like that.
A getter works its value out each time it is read; a setter runs when a value is assigned, and can refuse a bad one with an error. Keep the real value in a private field behind them. A getter with no setter makes the property read-only: an assignment is ignored, or throws in strict code.
Take a guess: How did a popular framework use setters to update a page whenever data changed?
The objects lesson met getters and setters on plain objects: properties that run a function when they are read or set. In a class they are written the same way, and they pair naturally with private fields.
A getter: a value worked out when it is read
A rectangle's area depends on its width and height. Stored as a property, it would go stale the moment the width changed. As a getter, it is worked out afresh on every read:
class Rect {
constructor(w, h) {
this.w = w;
this.h = h;
}
get area() {
return this.w * this.h;
}
}
const r = new Rect(3, 4);
r.w = 5;
console.log(r.area, typeof r.area);
20 number
The width changed to 5 after the rectangle was made, and the area read 20, not 12. A getter is read without brackets, r.area, like any property, and gives a plain value: typeof says number, not function.
A setter: checking what it is given
A setter runs when a property is assigned, and receives the new value. It can refuse a bad value before it does any harm. With a private field behind it, the setter is the only way in:
class Thermostat {
#celsius = 20;
get celsius() {
return this.#celsius;
}
set celsius(value) {
if (value < 10 || value > 30) throw new RangeError(`Temperature must be 10 to 30, got ${value}`);
this.#celsius = value;
}
}
const th = new Thermostat();
th.celsius = 24;
console.log(th.celsius);
th.celsius = 45;
24
Uncaught RangeError: Temperature must be 10 to 30, got 45
at set celsius (line 7)
at line 14
Read it as a story. th.celsius = 24 calls the setter with 24, which passes the check and is stored. Reading th.celsius calls the getter, which gives 24. th.celsius = 45 calls the setter again, which throws, so the private value stays 24. The stack trace names the setter: set celsius.
A getter with no setter
A getter alone makes a property that can be read but not set. Outside strict mode, a write to it is ignored without a word; in strict mode, which every module and class body uses, it is an error:
class Rect {
get area() {
return 12;
}
}
const r = new Rect();
r.area = 99;
console.log(r.area);
12
"use strict";
class Rect {
get area() {
return 12;
}
}
const r = new Rect();
r.area = 99;
Uncaught TypeError: Cannot set property area of #<Rect> which has only a getter
at line 8
| Written | Runs when | Used as |
|---|---|---|
get area() { return ...; } | the property is read | r.area, no brackets |
set celsius(value) { ... } | the property is assigned | th.celsius = 24 |
| a getter, and no setter | read only | a write is ignored, or a TypeError in strict code |
Worked example 3
A shop keeps prices in paise, as the values lesson advised, but its screens think in rupees. Write a class Price with a private #paise, a getter rupees that gives the amount in rupees, and a setter rupees that stores a rupee amount as whole paise and refuses a negative one.
What we have: an amount, set and read in rupees, stored in paise
What we need: a price that cannot be negative and is always whole paise
The plan: a private #paise; the getter divides by 100, and the setter checks the value, then multiplies by 100 and rounds
class Price {
#paise = 0;
get rupees() {
return this.#paise / 100;
}
set rupees(value) {
if (value < 0) throw new RangeError(`A price cannot be negative, got ${value}`);
this.#paise = Math.round(value * 100);
}
}
const tea = new Price();
tea.rupees = 12.5;
console.log(tea.rupees);
try {
tea.rupees = -3;
} catch (err) {
console.log(err.name, tea.rupees);
}
12.5
RangeError 12.5
The price reads ₹12.5, and the negative price is refused with a RangeError.
Check: after the refused write, tea.rupees still reads 12.5: the private paise were never changed.
A path that fails: a public field rupees = 0;. Any line can then set tea.rupees = -3 and the shop sells tea at a loss, with no error anywhere.
When you are stuck: a getter or setter does not behave
Read a getter without brackets: r.area, not r.area().
A getter and the field behind it need different names: get celsius reads this.#celsius.
A write that seems to vanish means there is a getter and no setter.
Inside a setter, check the value first, and store it last.
Your turn
class Circle {
constructor(r) {
this.r = r;
}
get diameter() {
return this.r * 2;
}
}
const c = new Circle(4);
c.r = 10;
console.log(c.diameter);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
20
- The getter is worked out when it is read.
- By then r is 10, so the diameter is 20.
It prints 20.
Why does a getter named celsius store its value in #celsius, and not in this.celsius?Tap to reveal
- this.celsius would call the getter or setter itself.
- A setter that assigned this.celsius would call itself, again and again.
Because this.celsius is the accessor itself; the value needs a field of its own.
What happens to r.area = 99 when Rect has only a getter for area, outside strict mode?Tap to reveal
- There is no setter to run.
- Outside strict mode, the write is ignored.
Nothing: the area still reads the getter's value.
Did you know?
Getters before classes
Getters are older than classes. The 5.1 edition of the standard, from June 2011, already let an object literal hold get and set definitions. A non-standard method, __defineGetter__, does the same job: it binds a property to a function that is called when the property is looked up. MDN marks it as deprecated in favour of the get syntax and Object.defineProperty.
Why it fits here: It shows that this topic's get and set inside a class reuse syntax that plain objects had years earlier.
Sources: ECMAScript 5.1 Language Specification; Ecma International: ECMA-262; MDN: Object.prototype.__defineGetter__()
Setters that redraw the page
Getters and setters once powered a whole framework. Vue 2's guide explains that it walks through every property of a component's data and converts each one into a getter and setter with Object.defineProperty. Reading or writing a property then lets Vue track what depends on what, and update the page. The guide adds that this ES5-only feature is why Vue 2 does not support IE8 and below.
Why it fits here: It answers this topic's question: Vue 2 put a setter on every data property, so each assignment could trigger an update of the page.
In one line
A getter works a value out each time it is read; a setter runs when a value is assigned, and can refuse a bad one. Keep the real value in a private field behind them, and remember that a getter alone makes the property read-only.
Static methods and fields
At a glance
A school's motto belongs to the school, not to any one student; asking a student for it makes no sense. Some methods and values belong to a class in the same way.
The word static makes a method or field belong to the class, not to its instances, so it is called on the class itself, as Money.fromRupees(12.5). Statics suit other ways of making objects, and values shared by the whole class. An instance cannot reach them through this. Asked on an instance, a static gives undefined.
Take a guess: Is Math a class whose methods are all static?
Some things belong to the pattern, not to any one object made from it: how many tickets have been sold, or a second way to make a ticket. These are written with the word static, and are used on the class itself, never on an instance.
A method written with static in a class body. It is called on the class, Money.fromRupees(12.5), and is not available on the instances. A static field is a value kept on the class in the same way.
A second way to make an object
A constructor takes its arguments in one form. A static method can offer another, and then call new itself. Such a method is called a factory method:
class Money {
static fromRupees(rupees) {
return new Money(Math.round(rupees * 100));
}
constructor(paise) {
this.paise = paise;
}
}
const m = Money.fromRupees(12.5);
console.log(m.paise, typeof m.fromRupees);
1250 undefined
Money.fromRupees(12.5) turns rupees into paise, 1250, and makes the object with them. The instance m has no fromRupees: typeof says undefined, because static methods live on the class alone. A name such as fromRupees says what the argument is, which a bare new Money(12.5) could not.
A value kept by the class
A static field holds one value for the whole class. Here every new ticket adds one to the class's count:
class Ticket {
static count = 0;
constructor() {
Ticket.count++;
}
}
new Ticket();
new Ticket();
console.log(Ticket.count);
2
Inside the constructor, the count is written Ticket.count, with the class's name, as it is not on this. Two tickets were made, so the count is 2. Built-in classes use the same idea: Number.isInteger, Array.isArray and Object.freeze are all static methods, called on the class, not on a number, an array or an object.
| Instance method | Static method | |
|---|---|---|
| written | describe() { ... } | static fromRupees(r) { ... } |
| called on | an instance: t.describe() | the class: Money.fromRupees(12.5) |
| this inside it | the instance | the class |
| good for | what each object does | making objects, counting them, checks on any value |
Worked example 4
A bus company's ticket numbers go up by one for every ticket sold, across the whole company: T1, T2, T3 and so on. Write a class BusTicket that gives each new ticket the next number from a static counter, and sell three tickets.
What we have: a counter shared by every ticket, and a number for each ticket
What we need: tickets numbered T1, T2 and T3
The plan: a static field holds the last number; the constructor adds one to it and stores the result on the new ticket
class BusTicket {
static last = 0;
constructor(route) {
BusTicket.last++;
this.number = `T${BusTicket.last}`;
this.route = route;
}
}
const tickets = ["Pune to Nashik", "Pune to Satara", "Pune to Kolhapur"].map((route) => new BusTicket(route));
console.log(tickets.map((t) => `${t.number} ${t.route}`).join(", "));
T1 Pune to Nashik, T2 Pune to Satara, T3 Pune to Kolhapur
The three tickets are numbered T1, T2 and T3.
Check: BusTicket.last is 3 after three tickets.
A path that fails: a field last = 0; without static. Every ticket then has its own last, starting at 0, and every ticket is numbered T1.
When you are stuck: a static method or field cannot be found
Call statics on the class, Money.fromRupees, never on an instance.
Inside the class, reach a static field by the class's name, Ticket.count, not this.count.
If every instance shows the same starting value, a static was written without static.
If each instance should have its own value, use an ordinary field instead.
Your turn
class Order {
static made = 0;
constructor() {
Order.made++;
}
}
const a = new Order();
new Order();
new Order();
console.log(Order.made, a.made);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
3 undefined
- Three orders were made, so the class's count is 3.
- The instance a has no made property.
It prints 3 undefined.
Is Array.isArray an instance method or a static method?Tap to reveal
- It is called on Array itself, with the value to check.
A static method.
Write a static method zero() for Money that makes a Money of 0 paise.Tap to reveal
- A static method can call new on its own class.
static zero() { return new Money(0); }
Did you know?
Math, all static
The best-known statics belong to an object that is not a class at all. MDN explains that Math is not a constructor: it cannot be used with new or called as a function, and all of its properties and methods are static. The standard says the same in its own words: Math cannot be used as a constructor with the new operator. So Math.max and Math.PI are used on Math itself.
Why it fits here: It answers this topic's question: Math works like a class made only of statics, though it is a plain object.
Sources: MDN: Math; ECMAScript Language Specification: The Math Object
A block that runs once
A class can run setup code of its own, once. A static initialization block, written static { ... } inside the class body, holds statements evaluated while the class is set up. MDN says this allows more flexible setup than static fields alone, such as a try...catch. TC39's list of finished proposals names Class Static Block, by Ron Buckton.
Why it fits here: It extends this topic's statics: besides static methods and fields, a class can hold a block of setup code that runs once.
Sources: MDN: Static initialization blocks; TC39: Finished Proposals
In one line
static makes a method or field belong to the class, not to its instances: call it on the class, as Money.fromRupees(12.5). Use statics for other ways of making objects and for values shared by the whole class.
One class built on another
At a glance
A geared bicycle is still a bicycle: it has wheels, pedals and brakes, and one or two things of its own. One class can be built on another in the same way.
class B extends A gives B everything that A has. B's constructor must call super(...) before it uses this, and super.method() reaches the parent's version of a method that B has replaced. Extend only when B is truly a kind of A; otherwise, give B an A to use.
Take a guess: Can a class extend a built-in such as Array, or the result of a function?
A bank has accounts, and some accounts are savings accounts: everything an account is, and an interest rate as well. Writing the savings account from nothing would repeat the account's code. Instead, one class can extend another and add only what is new.
The word in class Savings extends Account that makes Savings a subclass of Account: every Savings object has Account's methods too. Account is called the parent class, or superclass.
class Account {
constructor(owner) {
this.owner = owner;
}
describe() {
return `Account of ${this.owner}`;
}
}
class Savings extends Account {
constructor(owner, rate) {
super(owner);
this.rate = rate;
}
describe() {
return `${super.describe()}, interest ${this.rate}%`;
}
}
const s = new Savings("Asha", 7);
console.log(s.describe(), s instanceof Savings, s instanceof Account);
Account of Asha, interest 7% true true
Three new things are at work here, one at a time.
- super(owner) in the constructor runs the parent's constructor, which sets this.owner. A subclass's constructor must call super before it uses this.
- describe in Savings has the same name as Account's, so it replaces it for savings accounts. This is called overriding a method.
- super.describe() calls the parent's describe from inside the new one, so the new method adds to the old answer instead of repeating it.
A savings account is an instance of Savings and of Account too, so both instanceof tests are true. Code that works with any account can be handed a savings account and still work.
super comes first
Until super has run, the object does not exist yet, as the parent's constructor is the one that makes it. So using this before super is an error:
class Account {
constructor(owner) {
this.owner = owner;
}
}
class Savings extends Account {
constructor(owner, rate) {
this.rate = rate;
super(owner);
}
}
new Savings("Asha", 7);
Uncaught ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
at new Savings (line 8)
at line 12
The message is long, and it says exactly what to do: call super before this. A subclass that needs nothing new in its constructor can leave the constructor out; it then passes every argument to the parent's:
class Account {
constructor(owner) {
this.owner = owner;
}
}
class Savings extends Account {}
const s = new Savings("Ravi");
console.log(s.owner);
Ravi
Extend only for "is a"
Use extends when the new thing truly is a kind of the old one: a savings account is an account; a bell clock is a clock. When one thing only uses another, such as a shop that has a till, give it the other as a property instead. Long chains of subclasses are hard to follow, so most classes extend nothing, or one parent.
Worked example 5
The Clock Tower's bell clocks are clocks with a bell. Write a class Clock with a name and a method tell(hour), and a class BellClock that extends it, adds the number of strokes, and overrides tell to add the bell's strokes after the clock's own line.
What we have: a clock that tells the hour, and a kind of clock that also rings
What we need: a bell clock that reuses the clock's tell and adds its strokes
The plan: BellClock calls super(name) in its constructor, stores the strokes, and its tell calls super.tell(hour) and adds the bell
class Clock {
constructor(name) {
this.name = name;
}
tell(hour) {
return `${this.name} shows ${hour}.00`;
}
}
class BellClock extends Clock {
constructor(name, strokes) {
super(name);
this.strokes = strokes;
}
tell(hour) {
return `${super.tell(hour)}, ${"dong ".repeat(this.strokes).trim()}`;
}
}
const plain = new Clock("East clock");
const bell = new BellClock("North clock", 3);
console.log(plain.tell(3));
console.log(bell.tell(3));
East clock shows 3.00
North clock shows 3.00, dong dong dong
The bell clock says North clock shows 3.00, dong dong dong.
Check: the first part of the bell clock's line is Clock's own, made by super.tell.
A path that fails: copying Clock's tell into BellClock and adding the bell. When Clock's format changes, the bell clocks keep the old one, and the tower's clocks disagree.
When you are stuck: a subclass misbehaves
Must call super constructor means this was used before super(...): move super to the top of the constructor.
A method that seems to ignore the parent was overridden: call super.method() inside it to keep the parent's part.
Check that the subclass passes the parent's arguments to super, in the parent's order.
instanceof is true for the class and every parent above it.
Your turn
class Animal {
speak() {
return "...";
}
}
class Cow extends Animal {
speak() {
return "moo";
}
}
class Calf extends Cow {}
const c = new Calf();
console.log(c.speak(), c instanceof Animal);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
moo true
- Calf adds nothing, so it uses Cow's speak.
- A calf is a Cow, and a Cow is an Animal.
It prints moo true.
What does super(owner) do in a subclass's constructor?Tap to reveal
- It runs the parent's constructor with owner.
- Only after it may this be used.
It runs the parent's constructor, which sets up the object.
When should a class extend another, and when should it hold one as a property?Tap to reveal
- Extend when the new thing is a kind of the old one.
- Hold one when it only uses the other.
Is a: extend; has a: a property.
Did you know?
Built-ins can be extended
A class can be built on JavaScript's own built-ins. MDN notes that extends can subclass custom classes as well as built-in objects, so class Basket extends Array gives an array with methods of its own. Any constructor that can be called with new and has a prototype property can be the parent. The standard's grammar allows any expression of the right kind after extends.
Why it fits here: It widens this topic's extends: a class can build on Array or Error as easily as on a class of your own.
Sources: MDN: extends; ECMAScript Language Specification: Class Definitions
Extending an expression
The word after extends need not be a name. MDN explains that any expression that evaluates to a constructor may follow it, which is often used to make mixins: functions that take a class and return a new class built on it. A class can have only one parent, so mixins are how code collects abilities from several places, one layer at a time.
Why it fits here: It shows a trick built on this topic's extends: since one parent is the limit, functions can stack abilities onto classes.
Sources: MDN: extends; ECMAScript Language Specification: Class Definitions
In one line
class B extends A gives B everything A has; B's constructor must call super(...) before using this, and super.method() reaches the parent's version of an overridden method. Extend only when B is a kind of A.
Error classes of your own
At a glance
A hospital's report does not say only that something is wrong; it names the illness, so the right doctor can act. Errors work better with names of their own too.
class StockError extends Error, with super(message, options) and this.name set, gives a failure a kind of its own. Code can catch it with instanceof, deal with it, and throw other kinds on. Each kind can then be handled in its own way. And the error underneath can travel inside it as its cause, so nothing is lost.
Take a guess: Why might instanceof fail for an error class when code is compiled for old browsers?
The errors lesson caught errors by their kind: a TypeError means one thing, a RangeError another. Your own programs have kinds of failure of their own: a payment declined, a seat already booked, a form field left empty. A class that extends Error gives each of them a kind of its own, which a catch can recognise.
class PaymentError extends Error {
constructor(message, options) {
super(message, options);
this.name = "PaymentError";
}
}
try {
throw new PaymentError("Card declined for ₹450");
} catch (err) {
console.log(err.name, err.message, err instanceof PaymentError, err instanceof Error);
}
PaymentError Card declined for ₹450 true true
PaymentError extends Error, so it is a real error, with a message and a stack trace, and err instanceof Error is still true. super(message, options) hands the message to Error's own constructor. The one line of its own sets the name, so that every report says PaymentError.
Why the name needs setting
Error's constructor names every error Error. A subclass that does not set its own name is reported as a plain Error, which hides the very thing the class was made for:
class PaymentError extends Error {}
const e = new PaymentError("x");
console.log(e.name, String(e));
Error Error: x
With the name set, the error reads as itself, in String, in the Console and in an uncaught report:
class PaymentError extends Error {
constructor(message, options) {
super(message, options);
this.name = "PaymentError";
}
}
console.log(String(new PaymentError("Card declined")));
PaymentError: Card declined
class PaymentError extends Error {
constructor(message, options) {
super(message, options);
this.name = "PaymentError";
}
}
throw new PaymentError("Card declined");
Uncaught PaymentError: Card declined
at line 7
Catching by kind, and keeping the cause
A catch can now handle the failures it expects, and pass every other error on, as the errors lesson advised for errors it cannot deal with. When one error causes another, the second can carry the first as its cause, through the options object that Error's constructor takes:
class PaymentError extends Error {
constructor(message, options) {
super(message, options);
this.name = "PaymentError";
}
}
function pay(amount) {
try {
null.charge(amount);
} catch (err) {
throw new PaymentError(`Could not charge ₹${amount}`, { cause: err });
}
}
try {
pay(450);
} catch (err) {
if (!(err instanceof PaymentError)) throw err;
console.log(err.message);
console.log("because:", err.cause.name);
}
Could not charge ₹450
because: TypeError
The bank's library failed with a TypeError, deep inside. pay wrapped it in a PaymentError that says what the program was doing, with the TypeError kept as its cause for whoever debugs it. The outer catch handled the PaymentError it expected; any other kind would have been thrown on.
| Part | Why |
|---|---|
class PaymentError extends Error | a kind of its own, that is still an error |
super(message, options) | Error sets the message, the stack and the cause |
this.name = "PaymentError" | so that every report shows the kind |
err instanceof PaymentError | a catch recognises its own kind |
{ cause: err } | the error underneath is kept, not lost |
Worked example 6
A school's admission form must name the field that failed, so that the page can mark it in red. Write a class FieldError that extends Error and also stores the field, and a function check(form) that throws one for an empty name or an age under 3. Catch it and show the field.
What we have: a form with a name and an age
What we need: an error that says which field failed, caught by its kind
The plan: FieldError's constructor takes the field and the message, calls super(message), sets the name and stores the field; check throws it, and a catch reads err.field
class FieldError extends Error {
constructor(field, message) {
super(message);
this.name = "FieldError";
this.field = field;
}
}
function check(form) {
if (form.name === "") throw new FieldError("name", "Please write the child's name");
if (form.age < 3) throw new FieldError("age", `Age must be 3 or more, got ${form.age}`);
return "ok";
}
for (const form of [{ name: "Meera", age: 4 }, { name: "", age: 5 }, { name: "Kabir", age: 2 }]) {
try {
console.log(check(form));
} catch (err) {
if (!(err instanceof FieldError)) throw err;
console.log(`${err.field}: ${err.message}`);
}
}
ok
name: Please write the child's name
age: Age must be 3 or more, got 2
The first form passes; the others are refused at name and at age.
Check: each refusal names its field, which is what the page needs to mark it.
A path that fails: throwing a plain new Error("age: Age must be 3 or more") and reading the field back out of the message with split. Every change of wording then breaks the page, where a property would not.
When you are stuck: your own error class reports as Error
Set this.name in the constructor, after super.
Pass the message to super(message), or err.message is empty.
Pass options too, super(message, options), if you want to keep a cause.
In a catch, test err instanceof YourError, and throw any other kind on.
Your turn
class SeatError extends Error {
constructor(message) {
super(message);
this.name = "SeatError";
}
}
const e = new SeatError("Seat 42 is taken");
console.log(String(e), e instanceof Error);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
SeatError: Seat 42 is taken true
- String of an error is its name, a colon, and its message.
- A SeatError is an Error too.
It prints SeatError: Seat 42 is taken true.
What does err.name say for a subclass of Error that never sets its name?Tap to reveal
- Error's constructor names every error Error.
Error.
How does a catch handle only PaymentError and pass every other error on?Tap to reveal
- Test the kind, and throw anything else again.
if (!(err instanceof PaymentError)) throw err;
Did you know?
When instanceof broke
Compiling code for old browsers once broke error classes. TypeScript's notes on breaking changes explain that when classes are compiled to older JavaScript, subclassing Error may no longer work as expected: new FooError() instanceof FooError returns false. Their advice was to set the prototype by hand right after the super(...) call. Code compiled to modern JavaScript keeps real classes, where instanceof works.
Why it fits here: It explains odd advice in older code: a line that fixes the prototype after super, needed only when classes were compiled away.
A code, not a message
Node.js names its errors with codes as well as messages. Its documentation says the code property is a string label that identifies the kind of error, and the most stable way to identify one: a code changes only between major versions, while message text may change in any version. So code that catches a Node error should test err.code, not the words of its message.
Why it fits here: It adds a habit to this topic's own error classes: give each kind a stable name or code to test, and leave messages free to change.
Source: Node.js documentation: Errors
In one line
class MyError extends Error, with super(message, options) and this.name set, gives a failure a kind of its own. Catch it with instanceof, throw other kinds on, and keep the error underneath as its cause.
Where it is used
Classes are in the browser itself, in Node and in many libraries. Here is where each idea of this lesson does its work.
| What you learned | Where it is used | A real example |
|---|---|---|
| classes and new | many objects of one kind | new Date(), new Map(), new URL(address) |
| private fields | data that only the object may change | a wallet's balance, a clock's windings |
| getters and setters | values worked out or checked on the way in | an area from a width and height; a price that cannot be negative |
| static methods | other ways to make objects; checks on any value | Array.isArray(x), Money.fromRupees(12.5) |
| extends and super | a kind of a thing | a savings account; a bell clock |
| error classes | failures a program expects | PaymentError, FieldError, caught by their kind |
Mistakes and debugging
These are the slips that people meet most often with classes. Every output below is the real one, from the code shown.
1. A method taken off its object
class Wallet {
#balance = 100;
show() {
return this.#balance;
}
}
const w = new Wallet();
const f = w.show;
f();
Uncaught TypeError: Cannot read properties of undefined (reading '#balance')
at show (line 4)
at line 9
f is the method alone. Called without its object, its this is undefined, because class bodies are strict. The same happens when a method is handed to another function as a callback, such as to forEach, which calls it without its object. The fix: an arrow that calls it on its object, () => w.show(), or an arrow field in the class:
class Wallet {
#balance = 100;
show = () => this.#balance;
}
const w = new Wallet();
const f = w.show;
console.log(f());
100
An arrow has no this of its own, as lesson 01 showed, so an arrow field keeps the this of the instance it was made for. Each instance then has its own copy of the arrow, so keep this for methods that are passed around.
2. this before super
class Clock {
constructor(name) {
this.name = name;
}
}
class BellClock extends Clock {
constructor(name, strokes) {
this.strokes = strokes;
super(name);
}
}
new BellClock("North", 3);
Uncaught ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
at new BellClock (line 8)
at line 12
The fix: super(name) first, then this.strokes.
3. A class used without new
class Ticket {
constructor(fare) {
this.fare = fare;
}
}
const t = Ticket(350);
Uncaught TypeError: Class constructor Ticket cannot be invoked without 'new'
at line 6
The fix: new Ticket(350).
4. A getter called like a method
class Rect {
constructor(w, h) {
this.w = w;
this.h = h;
}
get area() {
return this.w * this.h;
}
}
const r = new Rect(3, 4);
console.log(r.area());
Uncaught TypeError: r.area is not a function
at line 11
r.area is already the number 12, and a number cannot be called. The fix: r.area, no brackets.
5. An error class that forgets its name
class SeatError extends Error {}
try {
throw new SeatError("Seat 42 is taken");
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}
Error: Seat 42 is taken
No error: the kind is lost in the report. The fix: a constructor that calls super(message) and sets this.name = "SeatError".
6. A class used above its declaration
const t = new Ticket(1);
class Ticket {
constructor(fare) {
this.fare = fare;
}
}
Uncaught ReferenceError: Cannot access 'Ticket' before initialization
at line 1
The fix: declare the class above the lines that use it.
The debugging corner: print the instance
When an object made from a class misbehaves, print it. Its line shows which class made it and its public properties, such as Item { name: 'tea', price: 15 }. A missing property means the constructor did not set it; a wrong class name means the wrong class was used. Private fields are not shown: add a method that reports them while you debug.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
The lesson in code
class Clock {
#windings = 0; // private: only the class can use it
static made = 0; // one value for the whole class
constructor(name) {
this.name = name; // each instance's own
Clock.made++;
}
wind() {
this.#windings++;
}
get windings() { // read like a property
return this.#windings;
}
tell(hour) {
return `${this.name} shows ${hour}.00`;
}
}
class BellClock extends Clock {
constructor(name, strokes) {
super(name); // the parent first, then this
this.strokes = strokes;
}
tell(hour) {
return `${super.tell(hour)}, ${"dong ".repeat(this.strokes).trim()}`;
}
}
class ClockError extends Error {
constructor(message) {
super(message);
this.name = "ClockError"; // so that reports show the kind
}
}
const north = new BellClock("North clock", 2);
north.wind();
console.log(north.tell(2), north.windings, Clock.made, north instanceof Clock);
console.log(String(new ClockError("Spring broken")));
North clock shows 2.00, dong dong 1 1 true
ClockError: Spring broken
| When you see | It means | Look at |
|---|---|---|
TypeError: Class constructor ... cannot be invoked without 'new' | a class called like a function | new |
SyntaxError: Private field '#...' must be declared in an enclosing class | a private field used outside its class | a method that reads it |
ReferenceError: Must call super constructor ... | this used before super in a subclass | super(...) first |
TypeError: Cannot read properties of undefined inside a method | a method called without its object | an arrow, or an arrow field |
TypeError: ... is not a function for a getter | a getter called with brackets | drop the brackets |
| an error reported as Error | an error class without its own name | this.name in its constructor |
The story: One pattern for every clock
You write the pattern once, as a class. Every clock made from it gets the same fields, spelt the same way, and the same methods. Its winding count is private: no line outside can set it, and the wind method only ever adds to it. The bell clocks get a pattern of their own, which extends the first and adds a bell.
The east clock chimes for the first time in years, and the west clock's count can no longer be set by hand.
Master Verge makes a new clock from the pattern, just to watch it work. "A pattern is a promise," he says. "Every clock made from it keeps it."
Reagents gathered: class, constructor, private field, getter, static method, extends.
Sources
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)
- The ECMAScript language specification (ECMA-262) (Ecma International copyright; facts and ideas only)