Accessing a super-class

All functions within a class defined using the method definition syntax have the super binding available, which provides access to the super-class and its properties. The super() function is available to invoke directly (which will call the constructor of the super-class) and can provide access to specific methods (super.methodName()).

If you are extending another class and you are defining your own constructor, you must call super() and you must do so before any other code within your constructor that modifies the instance (that is, this) in any way:

class Tiger extends Animal {
constructor() {
super(); // I.e. Call Animal's constructor
}
}

If your constructor attempts to call super() after modifying the instance, or if it attempts to avoid calling super(), then you will receive ReferenceError:

class Tiger extends Animal {
constructor() {
this.someProperty = 123;
super();
}
}

new Tiger();
// ! ReferenceError: You must call the super constructor in a derived class
// before accessing 'this' or returning from the derived constructor

The super binding and its oddities are described in greater detail in Chapter 6, Primitives and Built-in Types (see the section on Function bindings).

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

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