Inheritance Lesson

Inheritance lets one class build from another class. The parent class stores shared behavior, and the child class adds or changes details for a more specific type of object.

JavaScript uses extends to create the relationship. When a child class has its own constructor, it calls super to run the parent constructor before adding child-specific properties.

Code Runner Challenge

Inheritance Lesson

View IPYNB Source
%%js

// CODE_RUNNER: Inheritance Lesson

class Character {
  constructor(name, health) {
    this.name = name;
    this.health = health;
  }

  takeDamage(amount) {
    this.health = this.health - amount;
  }
}

class Guard extends Character {
  patrol() {
    console.log(this.name + " is patrolling");
  }
}

const guard = new Guard("Gate Guard", 50);
guard.takeDamage(10);
guard.patrol();
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Inheritance is helpful when multiple classes have the same base behavior. A Guard, Player, and Enemy might all have position and health, but each one can still add its own actions.