ILILCode
HomeJavaScriptAdvanced

Classes: blueprints for objects

Constructors, methods, getters, inheritance with extends, and truly private fields.

Lesson 14 of 23 in JavaScript12 min1 exercise

A class bundles data and the functions that work on it. new creates an instance, and the constructor sets it up. Methods live on the prototype, so all instances share them.

A class with a getter
class Cart {
  constructor(owner) {
    this.owner = owner;
    this.items = [];
  }

  add(item) {
    this.items.push(item);
    return this.items.length;
  }

  get total() {
    return this.items.length;
  }

  static empty() {
    return new Cart("guest");
  }
}

const cart = new Cart("Ada");
cart.add("pen");
cart.total;          // 1  — no parentheses, it is a getter
Cart.empty().owner;  // "guest"

extends builds on another class. Call super(...) before using this in the child constructor.

Inheritance
class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    return `${this.name} makes a sound`;
  }
}

class Dog extends Animal {
  speak() {
    return `${this.name} barks`;
  }
}

new Dog("Rex").speak(); // "Rex barks"
new Dog("Rex") instanceof Animal; // true

Try it

Inheritance in action

main.js
console · output appears here

Exercises

Checked in your browser · hints and solutions included

01

Exercise

Write a Stack class

Build a Stack class with:

  • push(value) — add to the top
  • pop() — remove and return the top value; throw an Error with the message Stack is empty when there is nothing to pop
  • peek() — return the top value without removing it (undefined when empty)
  • get size() — the current number of items

Keep the storage private.

exercise.js
console · run your code or check the answer