Skip to content

JavaScript extends | keyword

  • by

The extends keyword can be used to extend the objects as well as classes in JavaScript. The extends keyword can be used to subclass custom classes as well as built-in objects. In another word, its used to create a class that is a child of another class.

class childclass extends parentclass {
     //...}

class parentclass extends in-built object {
    //...}

JavaScript extends

Simple example code.

JavaScript extends class

inherit the methods from the “Car” class:

<!DOCTYPE html>
<html>
<body>
  <script>
    class Car {
      constructor(brand) {
        this.carname = brand;
      }
      present() {
        return 'I have a ' + this.carname;
      }
    }

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

    mycar = new Model("AUDI", "Q7");
    console.log(mycar.present());
    console.log(mycar)
  </script>

</body>
</html> 

Output:

JavaScript extends

Using extends object

This example extends the built-in Date object.

<script>
    class myDate extends Date {

      getFormattedDate() {
        var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        
        return this.getDate() + '-' + months[this.getMonth()] + '-' + this.getFullYear();
      }
    }

    var d = new myDate()
    console.log(d.getFormattedDate())

</script>

Output:

16-May-2022

Do comment if you have any doubts or suggestions on this JS extends keyword.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading