Classes and prototypes

15 min read javascript
Course contents (16 lessons)
  1. Modern syntax
  2. Destructuring, spread and rest
  3. ES modules: import and export
  4. Objects, this and errors
  5. Classes and prototypes
  6. Understanding this in JavaScript
  7. Error handling: try, catch and custom errors
  8. Asynchronous JavaScript
  9. The event loop: how JavaScript handles waiting
  10. From callbacks to promises to async/await
  11. Fetch and REST APIs
  12. Working in the browser
  13. Local storage and session storage
  14. Debugging with browser DevTools
  15. Performance basics: debounce and throttle
  16. Node.js essentials
  17. Node.js and npm basics
  18. Working with files in Node.js
  19. A tiny HTTP server with Node.js
  20. Testing and the final project
  21. Testing basics with the Node.js test runner
  22. Final project: a post explorer with modules and fetch

Making many similar objects

If you need one user object, an object literal is fine. If you need hundreds of users that all have the same shape and behaviour, you want a blueprint. In JavaScript, that is a class.

Class syntax

class BankAccount {
  constructor(owner, balance = 0) {
    this.owner = owner;
    this.balance = balance;
  }

  deposit(amount) {
    if (amount <= 0) throw new Error("Amount must be positive");
    this.balance += amount;
    return this;
  }

  withdraw(amount) {
    if (amount > this.balance) throw new Error("Insufficient funds");
    this.balance -= amount;
    return this;
  }

  describe() {
    return `${this.owner}: Rs. ${this.balance}`;
  }
}

const account = new BankAccount("Ali", 1000);
account.deposit(500).withdraw(200);
console.log(account.describe()); // Ali: Rs. 1300

constructor runs when you write new BankAccount(...). It sets up the properties of the new object. The methods are shared by all instances. Because deposit and withdraw return this, you can chain the calls.

Calling a class without new throws an error. That is a good thing, since it prevents a silent mistake.

Getters, setters and static members

class Temperature {
  constructor(celsius) {
    this.celsius = celsius;
  }

  get fahrenheit() {
    return this.celsius * 9 / 5 + 32;
  }

  set fahrenheit(value) {
    this.celsius = (value - 32) * 5 / 9;
  }

  static fromFahrenheit(value) {
    return new Temperature((value - 32) * 5 / 9);
  }
}

const t = new Temperature(100);
console.log(t.fahrenheit);                       // 212
t.fahrenheit = 32;
console.log(t.celsius);                          // 0
console.log(Temperature.fromFahrenheit(212).celsius); // 100

A getter looks like a property but runs code. A static method belongs to the class itself and is called on it, not on an instance. It is often used for alternative ways to create objects.

Private fields

A name starting with # is private. Code outside the class cannot read or write it.

class Counter {
  #count = 0;

  increment() {
    this.#count++;
    return this.#count;
  }

  get value() {
    return this.#count;
  }
}

const c = new Counter();
c.increment();
c.increment();
console.log(c.value);   // 2
// console.log(c.#count); // SyntaxError

Use private fields to protect state that should only change through your methods. This is real privacy, enforced by the language. It is different from the old habit of starting names with an underscore, which only asks other people politely not to touch them.

Inheritance

A class can extend another to reuse and specialise its behaviour.

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    return `${this.name} makes a sound`;
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name);          // must come before using this
    this.breed = breed;
  }
  speak() {
    return `${super.speak()}: woof`;
  }
}

const d = new Dog("Rex", "Labrador");
console.log(d.speak());                 // Rex makes a sound: woof
console.log(d instanceof Animal);       // true

super(name) calls the parent constructor. In a child class you must call it before you touch this. super.speak() calls the parent version of a method.

A word of advice from experience. Inheritance is easy to overuse. Deep chains of classes become rigid, and a change in the parent breaks children in surprising ways. Often a plain function, or an object that holds another object (composition), is simpler. I reach for extends only when there is a true "is a" relationship and it goes one level deep.

Prototypes: what is under the hood

JavaScript classes are a friendlier syntax over prototypes. Every object has a hidden link to another object, its prototype. When you read a property, JavaScript looks at the object first. If it is not there, it follows the link to the prototype, then to that object's prototype, and so on, until it reaches the end of the chain. This is the prototype chain.

const d = new Dog("Rex", "Lab");
console.log(Object.getPrototypeOf(d) === Dog.prototype);           // true
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); // true
console.log(d.hasOwnProperty("name"));    // true, set on the instance
console.log(d.hasOwnProperty("speak"));   // false, found on the prototype

Methods live once on Dog.prototype, not on every instance. That saves memory, and it is why changing a class method affects all existing objects. You do not need to touch prototypes directly in everyday code. Knowing the model helps you understand error messages and library code.

Common mistakes

  • **Forgetting new.** Calling BankAccount("Ali") throws a TypeError.
  • **Using this before super().** You get a ReferenceError in a subclass constructor.
  • Passing a method as a callback. button.addEventListener("click", account.describe) loses this. The next lesson covers this problem.
  • Putting commas between class methods. Class bodies do not use commas.
  • Deep inheritance. Prefer small classes that use other objects.

Try it yourself

  1. Create a Rectangle class with width, height and an area() method. Add a Square class that extends it.
  2. Add a private field #history to BankAccount that records each transaction, and a method that returns a copy of the history.
  3. Write a static method Temperature.compare(a, b) that returns the warmer one.
  4. Log Object.getPrototypeOf(account) for the account object and explain what you see.
javascript
class BankAccount {
  constructor(owner, balance = 0) {
    this.owner = owner;
    this.balance = balance;
  }

  deposit(amount) {
    if (amount <= 0) throw new Error("Amount must be positive");
    this.balance += amount;
    return this;
  }

  withdraw(amount) {
    if (amount > this.balance) throw new Error("Insufficient funds");
    this.balance -= amount;
    return this;
  }

  describe() {
    return `${this.owner}: Rs. ${this.balance}`;
  }
}

const account = new BankAccount("Ali", 1000);
account.deposit(500).withdraw(200);
console.log(account.describe()); // Ali: Rs. 1300

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account