JavaScript Classes

Classes are present in many programming languages. For using classes in Js, we use the class keyword. A class contains properties and methods. It supports constructor, to create some properties, inheritance etc. We use this keyword to use interact with methods and properties.

Eg:    // Human class

    class Human {
        constructor() {
            this.gender = "Male"    -> Property
        }
        printGender = () => {        -> Method
            console.log(this.gender);
        }
    }

    const newHuman = new Human();
    newHuman.printGender();

    // Inheritance
    class Person extends Human {
        constructor() {
            super();
            this.name = "Ayush"
            this.gender = "Female"
        }
        printMyName = () => {
            console.log(this.name);
        }
    }

    const newPerson = new Person();
    newPerson.printMyName();
    newPerson.printGender();

But, in modern JS, we can omit constructor and this keyword inside the constructor, also super, and directly create class.


Eg:   // Class without constructor keyword

     class Human {
      gender = "Male";
      printGender = () => {
        console.log(this.gender);
      };
    }

Comments