JS: super (keyword)
super
(new in JS: ECMAScript 2015)
There are 2 syntax of super
, with different meaning.
super(args)
-
used inside constructor, to call parent constructor.
super.prop
-
- used in method definition or object literal.
- It refers to parent object's property prop.
super() in Constructor
Suppose you have
B extends A {body}
super(args)
is a call to the constructor of parent class. i.e.super(args)
is similar tothis = new A(args)
.- In a derived class, inside a constructor,
super(args)
MUST be called. (Note, when no constructor is given, the default isconstructor () {super(args)}
) - In a derived class,
super(args)
must be called beforethis
keyword can be used.
example
class A { constructor(x) { console.log( "A constructor called with " + x ); this.k1 = x; } } 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 } } 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 }
super.‹prop› in Class Prototype Method
When super is used inside class prototype method, suppose you have
class B extends A {body}
- If
super.name
is used inside prototype method, then it refers toA.prototype.name
- If
super.name
is used inside static method, then it refers toA.name
class A { // prototype method. This is going to be in A.prototype.f f (x) {return x;} // static method. This is going to be in A.f static f (x) {return x;} } class B extends A { g () { return super.f; }; // the super.f here refers to A.prototype.f static g2 () { return super.f; } // the super.f here refers to A.f } console.log( (new B).g() === A.prototype.f ); // true console.log( B.g2() === A.f ); // true
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