JavaScript: Keyword “extends”

By Xah Lee. Date: . Last updated: .

New in JS2015.

The extends keyword is used together with the class. [see Class] It creates a constructor function. And, automatically creates 2 parent/child relationships.

here's a typical example of using extends.

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

  fA() {
    console.log("fA 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.k2 = y; // add its own property
  }

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

const xB = new Bb(3, 4);
// prints
// Bb constructor called with 3 4
// Aa constructor called with 3

console.log(xB); // Bb { k1: 3, k2: 4 }

xB.fA(); // prints: fA called
xB.fB(); // prints: fB called

// this works because
// parent of xB is Bb.prototype, which contains function fB
// parent of Bb.prototype is Aa.prototype, which contains function fA
// by inheritance, xB has access to both fB and fA

[see Class]

“extends” Syntax

class B extends A {body}

The A on the right side must be a constructor (or null). Typically, it should be a function object defined by keyword class or function, or builtin constructor object such as Array, Date, etc.

[see JavaScript Object Reference]

What Does “extends” Do Exactly?

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.log(Reflect.getPrototypeOf(Bb) === Aa);

// parent of Bb.prototype is Aa.prototype
console.log(Reflect.getPrototypeOf(Bb.prototype) === Aa.prototype);

Extend a Class with Constructor

Default constructor for base class is constructor() {}

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

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

Keyword “super”

Keyword “super”

JavaScript Constructor/Class

BUY
ΣJS
JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Property

Object and Inheritance

Array

Function

Constructor/Class

Iterable 🌟

Misc