JS: “extends” keyword

By Xah Lee. Date: . Last updated: .

Syntax

(new in ECMAScript 2015)

class B extends A {body}

The A on the right side must be a Constructor callable by “new” operator. (or null ). And it must have a Property key "prototype" whose value is a Object Type .

Typically, it should be a function object defined by keyword class or keyword function.

Builtin constructors such as Array (class), Date (class) , etc can also be extended, but is discouraged.

What does extends do

When you have

class B extends A {body}

Basically the following happens:

  1. Run class B {body}.
  2. Make the parent of B to be A.
  3. Make the parent of B.prototype to be A.prototype.
// create a class
class AA {}

// extend it
class BB extends AA {}

// parent of BB is AA
console.assert(
 Reflect.getPrototypeOf(BB) === AA,
);

// parent of BB.prototype is AA.prototype
console.assert(
 Reflect.getPrototypeOf(BB.prototype) === AA.prototype,
);

Example

// create a class
class AA {
  constructor(x) {
    console.log("AA constructor called with " + x);
    this.key_a = x;
  }

  f_a() {
    console.log("f_a called");
  }
}

class BB extends AA {
  // adding a property in constructor
  constructor(x, y) {
    console.log(`BB constructor called with ${x} ${y}`);
    super(x); // calls AA's constructor
    this.key_b = y; // add its own property
  }

  // add a method f_b
  f_b() {
    console.log("f_b called");
  }
}

const obj_b = new BB(3, 4);
// prints
// BB constructor called with 3 4
// AA constructor called with 3

console.log(obj_b); // BB { key_a: 3, key_b: 4 }

obj_b.f_a(); // prints: f_a called
obj_b.f_b(); // prints: f_b called

Extend a class with constructor

Default constructor for base class is constructor() {}

Default constructor for derived class is constructor(params) { super(params); }

When you extend a class, and if you create a new constructor, you must call the base class constructor first, by the syntax super(args).