Classes
Overview
When you need many objects with the same shape and behaviour — many users, many products, many timers — a class describes them once.
class Course {
constructor(title, chapters) {
this.title = title;
this.chapters = chapters;
}
describe() {
return `${this.title} has ${this.chapters} chapters`;
}
}
const js = new Course('JavaScript', 14);
js.describe(); // 'JavaScript has 14 chapters'A class is the blueprint; each object made from it is an instance. Class names start with a capital letter by convention.
The constructor
constructor runs once for each new. It receives the arguments and stores them on this, the new instance.
What new Course('JavaScript', 14) does, step by step:
- Creates a fresh, empty object.
- Links that object’s prototype to
Course.prototype, where the methods live. - Runs
constructorwiththisset to the new object. - Returns the object.
A constructor is a good place to check arguments, so invalid objects can’t exist:
class Course {
constructor(title, chapters) {
if (!title) throw new Error('A course needs a title');
this.title = title;
this.chapters = chapters ?? 0;
}
}If you don’t need to set anything up, you can leave the constructor out entirely.
Methods
Methods are written without the function keyword or commas between them. Inside, this is the instance the method was called on:
class Counter {
count = 0;
increment() {
this.count++;
return this; // returning this allows chaining
}
reset() {
this.count = 0;
return this;
}
}
const c = new Counter();
c.increment().increment().count; // 2Methods live on Counter.prototype, so a thousand counters share one copy of increment. Each counter has its own count, though.
Fields
You can declare properties directly in the class body, with a starting value:
class Cart {
items = [];
add(item) {
this.items.push(item);
}
get total() {
return this.items.reduce((sum, i) => sum + i.price, 0);
}
}Fields are set up fresh for every instance — each cart gets its own items array. They’re a tidy way to list an object’s properties in one place, even ones that start empty.
Getters and setters
get total() is a getter: you read it like a property (cart.total), but it runs code each time. A setter runs when you assign to the property, which is a good place for validation:
class Temperature {
#celsius = 0;
get fahrenheit() {
return this.#celsius * 9 / 5 + 32;
}
set fahrenheit(f) {
this.#celsius = (f - 32) * 5 / 9;
}
get celsius() {
return this.#celsius;
}
}
const t = new Temperature();
t.fahrenheit = 212;
t.celsius; // 100(The # makes a field private — see Private and static members.)
Arrow functions as fields
Methods can lose their this when passed as callbacks — for example button.addEventListener('click', cart.clear). One fix is to define the method as an arrow function field, which captures this permanently:
class Cart {
items = [];
clear = () => {
this.items = [];
};
}
button.addEventListener('click', cart.clear); // worksThe trade-off: each instance gets its own copy of the function, instead of sharing one on the prototype.
instanceof
js instanceof Course; // true
js instanceof Object; // true — everything is an Object underneath
typeof Course; // 'function' — a class is a special kind of functionClasses are prototypes underneath
The class syntax creates exactly the prototype structure from the previous topic:
Object.getPrototypeOf(js) === Course.prototype; // true
Object.hasOwn(js, 'title'); // true — data lives on the instance
Object.hasOwn(js, 'describe'); // false — methods live on the prototypeClasses are always strict and must be called with
new. CallingCourse()without it throws aTypeError.
Classes are also not hoisted like function declarations: you must define a class before the line that uses it.
Classes or plain objects?
You don’t need a class for every object. A single settings object or one-off record is perfectly fine as an object literal. Reach for a class when you’ll create many objects with the same behaviour, or when the objects have rules (validation, private state) worth keeping together with the data.
A Stopwatch class
Write a Stopwatch class with start(), stop() and an elapsed property (milliseconds between them). Add a reset() method, and make elapsed a getter that also works while the stopwatch is still running.
class Stopwatch {
// your code here
}class Stopwatch {
startedAt = null;
stoppedAt = null;
start() {
this.startedAt = Date.now();
this.stoppedAt = null;
}
stop() {
this.stoppedAt = Date.now();
}
reset() {
this.startedAt = null;
this.stoppedAt = null;
}
get elapsed() {
if (this.startedAt === null) return 0;
return (this.stoppedAt ?? Date.now()) - this.startedAt;
}
}Summary
- A class is a blueprint;
newcreates an instance from it. constructorsets up each new instance; fields declare properties with starting values.- Methods defined in the class live on its prototype and are shared by all instances.
- Getters and setters look like properties but run code.
- Classes are strict, not hoisted, and must be called with
new.