JS: super (keyword)

By Xah Lee. Date: . Last updated: .

Super

(new in 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}

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

example

class C_a {
 constructor(x) {
  console.log("C_a constructor called with " + x);
  this.key_a = x;
 }
}

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

const object_b = new C_b(3, 4);
// prints
// C_b constructor called with 3 4
// C_a constructor called with 3

console.log(object_b);
// C_b { key_a: 3, key_b: 4 }

Super.‹prop› in class prototype method

When super is used inside class prototype method, suppose you have

class B extends A {body}

  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 C_a {
 // prototype method. This is going to be in C_a.prototype.fun_a
 fun_a(x) {
  return x;
 }

 // static method. This is going to be in C_a.fun_a
 static fun_a(x) {
  return x;
 }
}

class C_b extends C_a {
 fun_b() {
  return super.fun_a;
 }
 // the super.fun_a here refers to C_a.prototype.fun_a

 static fun_2_b() {
  return super.fun_a;
 }
 // the super.fun_a here refers to C_a.fun_a
}

console.assert((new C_b()).fun_b() === C_a.prototype.fun_a);

console.assert(C_b.fun_2_b() === C_a.fun_a);