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.


RESETRUNFULL
<!DOCTYPE html><html><body><script>

//(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();                   // Doggie is eating some dog food.d.whoami();            // All animals are cute. All animals are                               // cute. I am a nice Dog. (late binding)Dog.comment();    // All animals are cute. All animals are cute.Dog.comment2();    // We should protect all animals.console.log(d.intro); // This dog is Doggie.d.drink();                // Doggie is drinking.console.log(d.constructor.name);  // Dog

</script></body><html>

Notice although this.this. this. constructor constructor 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.namemyObject.constructor.name 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.


RESETRUNFULL
<!DOCTYPE html><html><body><script>

class E extends Function {
   constructor(x) {
      super("return "+JSON.stringify(x)+";");
   }}console.log((new E(100))());    // 100

</script></body><html>