liveBook · Manning

Super keyword

As explained in Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond

A JavaScript keyword used in a subclass to invoke superclass constructors or access superclass methods and properties.

When a subclass needs to reuse setup or behavior from its parent class, `super` provides access to the superclass constructor and prototype methods. It works alongside class inheritance, which uses the prototype chain. section 28.0 section 28.2

Keep these rules in mind:

  • Call `super()` in a subclass constructor before referring to `this`; otherwise, the reference causes a `ReferenceError`. section 28.2
  • Use `super.method()` to invoke an overridden method on the superclass prototype. Class properties set on an instance cannot be accessed through `super`. section 28.2 section 28.4
  • An arrow-function class property is attached to the instance, not the prototype, so subclasses cannot call it through `super`. To keep a method extendable while binding it, define it as a method and bind it in the constructor. section 28.3
Listing 28.2. Invoking the superclass constructor with super
class TeamStore extends DataStore { constructor() { super('/teams'); 1 } }

A subclass can pass its fixed resource to the superclass constructor with `super()`. section 28.2

Listing 28.3. Invoking superclass methods with super
class ProductStore extends DataStore { fetch(id) { analytics.productWasViewed(id); return super.fetch(id); } }

An overridden `fetch` method can add analytics behavior, then delegate to the superclass implementation with `super.fetch(id)`. section 28.2

How Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond covers it

How deep it goes
Explains constructor ordering, prototype method access, and why instance class properties are unavailable through super.
Examples
Shows TeamStore passing a URL to DataStore, ProductStore extending fetch, and binding an overridable method.
What you can do after
Apply super to initialize subclasses before using this and extend superclass methods without discarding their behavior.
How it connects
Connects super with class inheritance, constructors, prototype methods, and instance properties.

Also explained in

Compare how 6 books explain super keyword →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond. The section links point to the parts of the book it draws on.