JS: extends (keyword)
Syntax
(new in JS: ECMAScript 2015)
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
orfunction
, or builtin constructor object such asArray
,Date
, etc.
What Does extends Do
When you have
class B extends A {body}
Basically the following happens:
- Run
class B {body}
. - Make the parent of
B
to beA
. - Make the parent of
B.prototype
to beA.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);
Example
// 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
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)
.
JavaScript. Constructor, Class
- JS: Constructor and Class
- JS: this (binding)
- JS: Constructor
- JS: prototype (property)
- JS: new (operator)
- JS: instanceof (operator)
- JS: constructor (property)
- JS: typeof, instanceof, .constructor
- JS: class (keyword)
- JS: Class Expression
- JS: typeof Class
- JS: static (keyword)
- JS: extends (keyword)
- JS: super (keyword)
- JS: Define a Class Without class