DEV Community 👩‍💻👨‍💻

Sujith V S
Sujith V S

Posted on

Classes in JavaScript

In programming, classes are the blueprints for objects.
A class mainly have properties and methods.
Properties are like 'Variables attached to classes'.
Methods are like 'functions attached to classes'.

Let's create a class named Person.

class Person {
    //js object constructor.
    constructor() {
        this.name = "Max";
    }

    printMyName() {
        console.log(this.name);
    }
}
Enter fullscreen mode Exit fullscreen mode

Above class 'Person' is having two things in it's body, a constructor function to create and initialise instance variable and a method 'printMyName()' to print the value in instance variable.
The above class 'Person' is a blueprint. In order to give life to this class, we have to create object for this class 'Person'.
Let's create an object for the class 'Person'.

const person = new Person();
person.printMyName();
Enter fullscreen mode Exit fullscreen mode

In the above code, we are creating an object using new keyword.
And we are calling the method 'printMyName()' to print the value in instance variable.

Inheritance
Like a child inherits the behaviour of his/her parents, we can also make a class inherits the methods and attributes of another class.
Let's create a inherited class,

class Human {
    constructor(){
        this.gender = 'male';
    }

    printGender() {
        console.log(this.gender);
    }
}

class Person extends Human {
    //js object constructor.
    constructor() {
        super();
        this.name = "Max";

    }

    printMyName() {
        console.log(this.name);
    }
}
Enter fullscreen mode Exit fullscreen mode

Here we use the keyword extends to make the class 'Person' inherits the methods and properties of the class 'Human'.
Also we use super() inside constructor function because, we are overriding the constructor function in class 'Person' and because of that the constructor function in class 'Human' won't have any effect. The super() function is used to give child class the access to methods and properties of a parent or sibling class.
Now let's create object from this inherited class,

const person = new Person();
person.printGender();
Enter fullscreen mode Exit fullscreen mode

Since we are inheriting the class 'Human' in class 'Person', we can access the method printGender() of 'Human' class from the class 'Person'.

Top comments (0)

Here is a post you might want to check out:

Regex for lazy developers

regex for lazy devs

Sorry for the callout 😆