JS: Keyword “extends”
New in ES2015.
The extends
keyword is used together with the class
. It creates a constructor function. And, automatically creates 2 parent/child relationships.
[see JS: Class]
Basic Example
First, here's a typical example of using extends
.
// create a class class A { constructor(x) { console.log ( "A constructor called with " + x ); this.k1 = x; } f () { console.log ( "f called" ) } } class B extends A { // adding a property in constructor constructor(x,y) { console.log ( `B constructor called with ${x} ${y}` ); super( x ); // calls A's constructor this.k2 = y; // add its own property } // add a method g g () { console.log ( "g called" ) } } const b = new B(3,4); // prints // B constructor called with 3 4 // A constructor called with 3 console.log ( b ); // B { k1: 3, k2: 4 } b.f(); // prints: f called b.g(); // prints: g called // this works because // parent of b is B.prototype, which contains function g // parent of B.prototype is A.prototype, which contains function f // by inheritance, b has access to both g and f
[see JS: 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:
- Run
class B {body}
. - Make the parent of
B
to beA
. - Make the parent of
B.prototype
to beA.prototype
.
// create a class class A {} // extend it class B extends A {} // parent of B is A console.log ( Object.getPrototypeOf ( B ) === A ); // parent of B.prototype is A.prototype console.log ( Object.getPrototypeOf ( B.prototype ) === A.prototype ); // true
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”
JS Constructor/Class
If you have a question, put $5 at patreon and message me.