Inheritance , Subclassing, Late Binding

A class/type may inherit/extend another class/type. The subclass/child class is said to derive the methods and properties of the superclass/parent class.


//(continues from the example in 8.6.1)
class Dog extends Animal {
  constructor(n, a, c) {
    super(n, a);
    this.color = c;
  }

  eat() { // method overriding
    console.log(this.name + ' is eating some dog food.');
  }

  static comment() { // method overriding
    super.comment();
    super.comment();
  }

  get intro() { // method overriding
    return 'This dog is ' + this.name + '.';
  }
}

var d = new Dog('Doggie', 2, 'White');
d.eat();
d.whoami(); // (late binding)
Dog.comment();
Dog.comment2();
console.log(d.intro);
d.drink();
console.log(d.constructor.name);

Doggie is eating some dog food. All animals are cute. All animals are cute. I am a nice Dog. All animals are cute. All animals are cute. We should protect all animals. This dog is Doggie. Doggie is drinking. Dog

Notice although this.constructor is used from the parent class, it references the value/method of the child class. This is called late (static) binding. Furthermore, as in the last line, myObject.constructor.name is the way to obtain the class name of an object.

You can use 'extends' with built-in objects such as Error, Date, and Promise too. The following attempts to extend the Function object.


class E extends Function {
  constructor(x) {
    super("return " + JSON.stringify(x) + ";");
  }
}

console.log((new E(100))());

100