Learn / Programming / JavaScript / Classes and Inheritance

JavaScript · Lesson 10 of 15

Classes and Inheritance

class syntax, constructors, static members, getters and extends.

  • Intermediate
  • 14 min read
  • 3 objectives

Before this lessonLesson 9: Objects, this and Prototypes

What you will learn

  • Write a class
  • Use extends and super
  • Add private fields

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 3 hours

Create a free account to keep your progress on every device.

The class keyword is friendlier syntax over the prototype system. It bundles data and the functions that work on it.

A class

class Account {
  #balance = 0;                 // private field
  static count = 0;

  constructor(owner) {
    this.owner = owner;
    Account.count++;
  }
  deposit(n) {
    if (n <= 0) throw new Error("positive only");
    this.#balance += n;
    return this;                // allows chaining
  }
  get balance() { return this.#balance; }
}

const a = new Account("Ada");
a.deposit(50).deposit(25);
console.log(a.balance, Account.count);
console.log(a.owner);
Output
75 1
Ada
  • #name fields are truly private; code outside the class cannot read them.
  • static members belong to the class, not to instances.
  • A get accessor reads like a property but runs code.

Inheritance

class Shape {
  area() { return 0; }
  describe() { return `${this.constructor.name} with area ${this.area()}`; }
}
class Square extends Shape {
  constructor(side) { super(); this.side = side; }
  area() { return this.side ** 2; }
}
console.log(new Square(4).describe());
console.log(new Square(2) instanceof Shape);
Output
Square with area 16
true

Classes are not always the answer

Plain objects and functions are often simpler. Reach for a class when you have many instances that share behaviour and need to keep private state.

Up next · Lesson 11Modules: import and exportSplit code into files with ES modules and use npm packages.