Constructors and super() Lesson

Constructor chaining means a child class constructor calls the parent class constructor. In JavaScript, this happens with super. The parent handles the shared setup, and the child adds extra details afterward. A child constructor must call super before using this. That rule exists because the parent constructor creates the base part of the object.

Code Runner Challenge

Constructors and super() Lesson

View IPYNB Source
%%js

// CODE_RUNNER: Constructors and super() Lesson

class Item {
  constructor(name, value) {
    this.name = name;
    this.value = value;
  }
}

class Weapon extends Item {
  constructor(name, value, damage) {
    super(name, value);
    this.damage = damage;
  }
}

const sword = new Weapon("Iron Sword", 25, 8);
console.log(sword.name + " does " + sword.damage + " damage");
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Weapon calls super to reuse the Item setup for name and value. After that, it adds the damage property that only weapons need.