Classes

Programming Languages · JavaScript Objects · 15 min

Use classes as blueprints to build many objects with the same shape and methods.

A class is a blueprint

A class is a blueprint for making objects. Its constructor runs when you make a new object, and sets it up using this. Make an object from a class with new.

class Dog {
  constructor(name) {
    this.name = name;
  }
}
const rex = new Dog("Rex");
console.log(rex.name); // Rex
  • Create a class Cat whose constructor takes name and stores it in this.name.

  • Make const cat = new Cat("Luna") and print cat.name.

A constructor with several values

A constructor can take as many values as you need. Store each one on this.

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}
  • Give Book a constructor that takes title and pages and stores both.

  • Make const book = new Book("Dune", 412) and print Dune has 412 pages using book.title and book.pages.

Methods in a class

Methods go inside the class, after the constructor, with no function keyword. Every object made from the class gets them, and this is that object.

class Lamp {
  constructor() {
    this.on = false;
  }
  toggle() {
    this.on = !this.on;
  }
}
  • Add a method increase() to Counter that adds 1 to this.count.

  • Call counter.increase() three times, then print counter.count.

Many objects, one class

The real power of a class: write it once, make as many objects as you like. Each one has its own values but shares the same methods.

const a = new Pet("Rex", "woof");
const b = new Pet("Tom", "meow");
  • Make two pets: "Rex" who says "woof" and "Tom" who says "meow".

  • Call speak() on both pets.

extends: building on another class

extends makes a new class that gets everything from an existing one, and then adds its own extras.

class Vehicle {
  constructor(name) { this.name = name; }
}
class Bike extends Vehicle {
  ring() { console.log("Ring ring!"); }
}

A Bike uses Vehicle's constructor, so new Bike("BMX") still sets name.

  • Create class Bird extends Animal with a method fly() that prints the bird's name and flies away.

  • Make new Bird("Kiwi"), then call its describe() and fly() methods.

Put it together: a bank account

Build a class from scratch: a constructor that sets things up, and methods that change the object. Then take it for a spin.

  • Create class BankAccount whose constructor takes owner, stores it, and sets this.balance to 0.

  • Add deposit(amount) that adds to the balance and withdraw(amount) that takes it away.

  • Make an account for "Zoe", deposit 50, deposit 20, withdraw 30, then print Zoe has $40 using its owner and balance.

More in JavaScript Objects

Previous: Objects · Next: Closures and Scope