JS: extends (keyword)
Syntax
(new in 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
classorfunction, 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
Bto beA. - Make the parent of
B.prototypeto beA.prototype.
// create a class class C_a {} // extend it class C_b extends C_a {} // parent of C_b is C_a console.log(Reflect.getPrototypeOf(C_b) === C_a); // parent of C_b.prototype is C_a.prototype console.log(Reflect.getPrototypeOf(C_b.prototype) === C_a.prototype);
Example
// create a class class C_a { constructor(x) { console.log("C_a constructor called with " + x); this.key_a = x; } f_a() { console.log("f_a called"); } } class C_b extends C_a { // adding a property in constructor constructor(x, y) { console.log(`C_b constructor called with ${x} ${y}`); super(x); // calls C_a'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 C_b(3, 4); // prints // C_b constructor called with 3 4 // C_a constructor called with 3 console.log(obj_b); // C_b { 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).