JS: Keyword “super”

By Xah Lee. Date: . Last updated: .

New in ES2015.

The keyword “super” is part of JavaScript syntax, it's not a method nor standalone concept.

There are 2 syntax of super, with different meaning.

  1. super(…) → used inside constructor, to call parent constructor.
  2. super.prop → used in any method definition or object literal. It refers to parent object's property prop.

super() in Constructor

Suppose you have

B extends A {…}

  1. super(…) is a call to the constructor of parent class. i.e. super(param) is similar to this = new A(param).
  2. In a derived class, inside a constructor, super(…) MUST be called. (Note, when no constructor is given, the default is constructor () {super(…)})
  3. In a derived class, super(…) must be called before this keyword can be used.

Here's a typical example use of super in constructor.

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 {…}

  1. If super.name is used inside prototype method, then it refers to A.prototype.name
  2. If super.name is used inside static method, then it refers to A.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

ECMAScript® 2016 Language Specification#sec-super-keyword

JS Constructor/Class

  1. “this” Binding
  2. What's Constructor?
  3. Property Key "prototype"
  4. Operator “new”
  5. Operator “instanceof”
  6. Property Key “constructor”
  7. Class
  8. Keyword “extends”
  9. Keyword “super”
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog