Loading

Inheritance

  • Inheritance is a fundamental concept in object-oriented programming,
  • It allows you to create new objects based on existing objects, thereby sharing and reusing code and behaviors.
  • In JavaScript, inheritance is achieved using prototypes and constructor functions or classes. 

Example:

  • displays the year value from a given date
<!DOCTYPE html>
<html>

<body>

  <script>
    class Moment extends Date {
      constructor(year) {
        super(year);
      }
    }
    var m = new Moment("August 15, 1947 20:22:10");
    document.writeln("Year value:")
    document.writeln(m.getFullYear());
  </script>

</body>

</html>

Output:

Year value: 1947

Custom class:

  • We declare the subclass and it will extend the properties of its parent class.

Example:

<!DOCTYPE html>
<html>

<body>

  <script>
    class Bike {
      constructor() {
        this.company = "Honda";
      }
    }
    class Vehicle extends Bike {
      constructor(name, price) {
        super();
        this.name = name;
        this.price = price;
      }
    }
    var v = new Vehicle("Honda", "40000");
    document.writeln(v.company + " " + v.name + " " + v.price);
  </script>

</body>

</html>

Output:

Honda 40000