Classes

Topic 2 of 4 in Classes & prototypes6 min readBeginnerFree course

Overview

When you need many objects with the same shape and behaviour — many users, many products, many timers — a class describes them once.

JavaScript
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 class Course is a blueprint. Its describe method is stored once on Course.prototype. new Course(‘JavaScript’, 14) and new Course(‘SQL’, 6) each create an instance holding their own title and chapters, and both link to the shared prototype.

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:

  1. Creates a fresh, empty object.
  2. Links that object’s prototype to Course.prototype, where the methods live.
  3. Runs constructor with this set to the new object.
  4. Returns the object.

A constructor is a good place to check arguments, so invalid objects can’t exist:

JavaScript
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:

JavaScript
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; // 2

Methods 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:

JavaScript
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:

JavaScript
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:

JavaScript
class Cart {
  items = [];
  clear = () => {
    this.items = [];
  };
}

button.addEventListener('click', cart.clear); // works

The trade-off: each instance gets its own copy of the function, instead of sharing one on the prototype.

instanceof

JavaScript
js instanceof Course; // true
js instanceof Object; // true — everything is an Object underneath
typeof Course;        // 'function' — a class is a special kind of function

Classes are prototypes underneath

The class syntax creates exactly the prototype structure from the previous topic:

JavaScript
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 prototype

Classes are always strict and must be called with new. Calling Course() without it throws a TypeError.

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.

Exercise

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.

JavaScript
class Stopwatch {
  // your code here
}

Summary

  • A class is a blueprint; new creates an instance from it.
  • constructor sets 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.