Inheritance

Inheritance, Subclassing and Late Binding

extends links two chains: Dog.prototype inherits from Animal.prototype, and Dog inherits from Animal, so statics are inherited too. A subclass constructor must call super() before using this, and super.method() reaches the parent's version. Inherited whoami() calls this.eat() and this.constructor.name, which resolve on the actual object at run time: late binding. Built-ins such as Error or HTMLElement (Web Components) can be extended too.

Overriding, super and late binding (continues the previous listing)JavaScriptLive
class Dog extends Animal {
  constructor(name, color) { super(name); this.color = color; }  // super() before `this`
  eat() { return `${super.eat()} Dog food!`; }                     // override calls parent
  static comment() { return `${super.comment()} Dogs too.`; }      // statics inherit too
}
const d = new Dog('Doggie', 'white');
console.log(d.whoami(), Dog.comment(), d instanceof Animal, Object.getPrototypeOf(Dog) === Animal);
class Dog extends Animal: solid arrows are [[Prototype]] links, dashed arrows the prototype property
class Dog extends Animal: solid arrows are [[Prototype]] links, dashed arrows the prototype property