CPCODELAB
JavaScript

Classes and Inheritance

11 min read

Classes

ES2015 class syntax is syntactic sugar over JavaScript's prototype-based inheritance. Classes make OOP patterns easier to read and write.

javascript
class Animal {
  #name; // private field (ES2022)

  constructor(name, sound) {
    this.#name = name;
    this.sound = sound;
  }

  speak() {
    console.log(this.#name + " says " + this.sound);
  }

  get name() { return this.#name; }

  static create(name, sound) {
    return new Animal(name, sound);
  }
}

const dog = new Animal("Rex", "woof");
dog.speak(); // Rex says woof
dog.name;    // "Rex"
Animal.create("Cat", "meow").speak();

Inheritance with extends and super

javascript
class Dog extends Animal {
  constructor(name, breed) {
    super(name, "woof"); // must call super() first
    this.breed = breed;
  }

  fetch(item) {
    console.log(this.name + " fetches the " + item);
  }
}

const rex = new Dog("Rex", "Labrador");
rex.speak();        // Rex says woof (inherited)
rex.fetch("ball");  // Rex fetches the ball
console.log(rex instanceof Dog);    // true
console.log(rex instanceof Animal); // true

Private class fields (prefix #) are truly private — not just by convention. Trying to access dog.#name outside the class throws a SyntaxError. This is a big improvement over the old underscore-prefix convention.

Ready to test yourself?
Practice JavaScript— quiz & coding exercises