Search code examples
javascriptinheritancefrontendsuper

Javascript Inheritance (super)


I was going through the JS inheritance documentation and I was greeted into a new "feature" (for me), called super, the keyword super. Well, from what I can understand, if I have a parent class called for example hospitalStaff with an argument of name and staff number and the inherited class is called nurse and also has the argument name on it but also other arguments. So, in this example I would just use super(name);, wouldn't I?

Thanks for helping!! Have a great day and happy coding!


Solution

  • Yes, you'd pass the parameters to the super function. By calling super in the Nurse constructor you call the constructor in the HospitalStaff and pass the parameters with them.

    In the example below the Nurse class also has the sayName method. All methods (including the constructor) are inherited from the parent class.

    But if your Nurse constructor is different than the one from HospitalStaff then you need to create a new constructor which also calls the constructor of the parent by using super. Without calling super you would just overwrite the child constructor. Try it out, it would still work. But you'll won't have the name and staffNumber properties.

    Same goes for methods where you can use super to call methods from the parent. This way you can overwrite a method from the child but still keep parent's implementation of that method.

    class HospitalStaff {
      constructor(name, staffNumber) {
        this.name = name;
        this.staffNumber = staffNumber;
      }
      sayName() {
        console.log(`Name: ${this.name}`);
        console.log(`Number: ${this.staffNumber}`);
      }
    }
    
    class Nurse extends HospitalStaff {
      constructor(name, staffNumber, field) {
        super(name, staffNumber); // Sets name and staffNumber properties
        this.field = field; // Adds a field property
      }
      sayName() {
        super.sayName();
        console.log(`Field: ${this.field}`);
      }
    }
    
    const bob = new HospitalStaff('bob', 43);
    bob.sayName();
    
    const julie = new Nurse('Julie', 120, 'pediatrics');
    julie.sayName();