HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Class Inheritance

To create a class inheritance, use the extends keyword. A class created with class inheritance inherits all the methods from another class. This allows you to build hierarchical relationships and reuse code efficiently.


The extends Keyword

Inheritance allows a "child" class to inherit logic from a "parent" class.

class Car {
  constructor(brand) {
    this.carname = brand;
  }
  present() {
    return 'I have a ' + this.carname;
  }
}

class Model extends Car {
  constructor(brand, mod) {
    super(brand); // Calls the parent constructor
    this.model = mod;
  }
  show() {
    return this.present() + ', it is a ' + this.model;
  }
}

let myCar = new Model("Ford", "Mustang");
console.log(myCar.show());

The super() Method

The super() method refers to the parent class. By calling the super() method in the constructor, we call the parent's constructor method and gets access to the parent's properties and methods.


Getters and Setters

Classes also allow you to use getters and setters. It can be smart to use getters and setters for your properties, especially if you want to do something special with the value before returning them, or before setting them.

class Car {
  constructor(brand) {
    this._carname = brand;
  }
  get carname() {
    return this._carname.toUpperCase();
  }
  set carname(x) {
    this._carname = x;
  }
}
Technical Note: Even if the getter is a method, you do not use parentheses when you want to get the property value: myCar.carname.

Key Points to Remember

  • Use extends to create a subclass (child)
  • The super() method is mandatory in the child constructor
  • Inheritance allows for better Code Reusability
  • Getters (get) and Setters (set) provide controlled access to data
  • A child class can override methods of its parent
  • Use the underscore prefix (e.g., _carname) to indicate "private" or internal properties