Skip to content

Introduction to Classes

A class is a template for creating objects that share the same shape and methods. You declare it with class, give it a constructor that sets up each new object, and list the methods that every instance can call. You then create instances with new.

Classes arrived in ES2015 as a clearer syntax for what constructor functions and prototypes already did, and JavaScript still uses prototypes underneath. Classes vs Prototypes shows the two side by side.

The constructor runs once for each new, and this inside it is the new object. Methods written in the class body are shared by every instance:

class Book {
constructor(title, author, pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
describe() {
return `${this.title} by ${this.author}, ${this.pages} pages`;
}
}
const book = new Book('Emma', 'Jane Austen', 474);
console.log(book.describe());
console.log(typeof Book);

This prints:

Emma by Jane Austen, 474 pages
function

typeof reports function, because a class is a special kind of function. Methods in the class body take no function keyword and are not separated by commas.

A get method is read like a property, with no brackets, and a set method runs when the property is assigned, which makes it a good place for validation. A field whose name starts with # is private: only code inside the class body can read or change it.

class Book {
#price;
constructor(title, price) {
this.title = title;
this.price = price;
}
get price() {
return this.#price;
}
set price(value) {
if (value < 0) {
throw new RangeError('Price cannot be negative');
}
this.#price = value;
}
get label() {
return `${this.title}: £${this.#price.toFixed(2)}`;
}
}
const book = new Book('Emma', 8.99);
console.log(book.label);
book.price = 6.5;
console.log(book.label);
try {
book.price = -1;
} catch (err) {
console.log(err.message);
}
console.log(Object.keys(book));

This prints:

Emma: £8.99
Emma: £6.50
Price cannot be negative
[ 'title' ]

The constructor assigns this.price, so even the first price goes through the setter. The private field does not appear in Object.keys(), and writing book.#price outside the class is a syntax error. Getters & Setters covers accessors in more detail.

A static method or field belongs to the class itself rather than to its instances. It suits helpers and counters that concern the class as a whole:

class Book {
static count = 0;
constructor(title) {
this.title = title;
Book.count++;
}
static byTitle(a, b) {
return a.title.localeCompare(b.title);
}
}
const shelf = [new Book('Persuasion'), new Book('Emma'), new Book('Middlemarch')];
shelf.sort(Book.byTitle);
console.log(shelf.map((b) => b.title));
console.log(Book.count);
console.log(typeof shelf[0].byTitle);

This prints:

[ 'Emma', 'Middlemarch', 'Persuasion' ]
3
undefined

Instances cannot see static members, which is what the last line shows.

extends makes one class build on another. In the child’s constructor, super(...) calls the parent’s constructor, and it must run before the constructor uses this. Inside a method, super.method() calls the parent’s version of a method that the child has overridden:

class Book {
constructor(title, pages) {
this.title = title;
this.pages = pages;
}
describe() {
return `${this.title}, ${this.pages} pages`;
}
}
class Ebook extends Book {
constructor(title, pages, sizeMb) {
super(title, pages);
this.sizeMb = sizeMb;
}
describe() {
return `${super.describe()}, ${this.sizeMb} MB download`;
}
}
const ebook = new Ebook('Middlemarch', 880, 2.4);
console.log(ebook.describe());
console.log(ebook instanceof Ebook, ebook instanceof Book);

This prints:

Middlemarch, 880 pages, 2.4 MB download
true true

Static members are inherited too, so Ebook would also have any static method defined on Book.

A class cannot be called without new:

class Book {}
try {
Book();
} catch (err) {
console.log(err.message);
}

This prints:

Class constructor Book cannot be invoked without 'new'

Class declarations are also not hoisted the way function declarations are, so using a class before the line that declares it throws a ReferenceError. The code inside a class body always runs in strict mode.

Steve Griffith covers this topic in his video Intro to JavaScript Classes.