super

The super keyword comes in three distinct flavors:

  • super() as a direct function invocation will call the superclass's constructor (that is, its object's  [[Prototype]] constructor) and is only valid to call within a constructor. It also must be called before trying to access this as it is super() itself that'll initiate the execution context.
  • super.property will access a property on the superclass (that is, the [[Prototype]]), and is only valid to reference within a constructor or method defined using the method definition syntax.
  • super.method() will invoke a method on the superclass (that is, the [[Prototype]]), and is only valid to call within a constructor or method defined using the method definition syntax.

The super keyword was introduced to the language at the same time as the class definition and method definition syntax, so it is tied up in those constructs. You are free to use super in class constructors, methods, and also in method definitions within object literals:

const Utils {
constructor() {
super(); // <= I can use super here
}
method() {
super.method(); // <= And here...
}
}

const utils = {
method() {
return super.property; // <= And even here...
}
};

The super keyword, as its name suggests, is semantically suited to referencing a superclass, so 99% of its valid use cases will be within class definitions, where you're seeking to reference the class being extended, like so:

const Banana extends Fruit {
constructor() {
super(); // Call the Fruit constructor
}
}

Using super in this manner is entirely intuitive, especially to programmers who are used to other OOP languages. For individuals adept with JavaScript's prototype mechanism, however, the implementation of super can seem confusing. Unlike the this value, super is bound at definition time, instead of call time. We've seen how we can manipulate the value of this by calling a method in a specific manner (for example, using fn.call()). You cannot similarly manipulate super. Hopefully, this will not affect you in any way, but it is useful to remember nonetheless.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.54.6