1. Subtyping with Constructor-Based Classes

Before the version ES2015, JavaScript did not have an explicit class concept and subtyping was not directly supported, so it had to be implemented with the help of certain code patterns providing two inheritance mechanisms: (1) inheritance of properties and (2) inheritance of methods.

As we have explained in Chapter 1 of Volume 1 , classes can be defined in two alternative ways: constructor-based and factory-based. Both approaches have their own way of implementing inheritance.

We summarize the ES2015 code pattern for defining a superclass and a subclass in a constructor-based single-inheritance class hierarchy with the help of the following example:

First, we define a base class, Person, with two properties, firstName and lastName, defined with getters and setters:

class Person {
  constructor ({first, last}) {
    // assign properties by invoking their setters
    this.firstName = first; 
    this.lastName = last; 
  }
  get firstName() {return this._firstName;}
  set firstName( f) {
    ... // check constraints
    this._firstName = f;
  }
  get lastName() {return this._lastName;}
  set lastName( l) {
    ... // check constraints
    this._lastName = l;
  }
}

Then, we define a subclass, Student, with one additional property, studNo:

class Student extends Person {
  constructor ({first, last, studNo}) {
    // invoke constructor of superclass
    super({first, last});
    // assign additional properties
    this.studNo = studNo;
  }
  get studNo() {return this._studNo;}
  set studNo( sn) {
    ... // check constraints
    this._studNo = sn;
  }
}

Notice how the constructor of the superclass is invoked: with super({first, last}).