Understanding Classes in JavaScript

Understanding Classes in JavaScript

In JavaScript, classes are a way to define a template from which you can create objects that have similar property values as that class; and also define methods that can be applied to those objects. Its main purpose is to promote code reusability.

In this article, we are going to demonstrate how to create a new class, define methods within the class, create new instances of the class, and apply those methods to them.

How to create a class

Here's a step-by-step process on how to create a class in JavaScript:

  1. Declare the class: To declare a class, use the class keyword followed by the name of the class as shown in this example below:

     class Person {
    
     }
    

    The name of the class usually begins with a capital letter according to naming conventions in JavaScript.

  2. Define the constructor: A constructor is a special method used to define the initial state of the class properties. Every time you create a new instance of the class, the constructor is called automatically on that instance. There can only be one constructor per class. The constructor can be defined using the constructor keyword:

     class Person {
         constructor {
         }
     }
    
  3. Define the properties within the constructor: Properties are values used to store data that is particular to a class. They can be defined within the constructor or within any other method in the class. Each property represents a value that will be set when a new instance of the class is created. In the example below, the properties defined for this class are "name" and "age".

     class Person {
         constructor (name, age) {
             this.name = name;
             this.age = age;
         }
     }
    
  4. Define the methods within the class: Methods are functions defined within a class. Methods can be called on new instances of the class using the this keyword.

     class Person {
         constructor (name, age) {
             this.name = name;
             this.age = age;
         }
         sayHello() {
             return(`Hello, I am ${this.name} and I am ${this.age} years old.`);
         }
     }
    

    In the example above, sayHello is a method that returns a string, while this.name and this.age refer to the property values (name and age) of the current instance the method is being applied on.

  5. Create new instances of the class: An instance of a class is an object that is created based on the template defined in the class. If a class can be likened to a blueprint for creating objects, then an instance of the class is an object created using that blueprint. In the example below, new persons ('person1' and 'person2') are created from the 'Person' class.

     class Person {
         constructor (name, age) {
             this.name = name;
             this.age = age;
         }
         sayHello() {
             return(`Hello, I am ${this.name} and I am ${this.age} years old.`);
         }
     }
    
     const person1 = new Person('Levai', 23);
     const person2 = new person ('Ayo', 30);
    
  6. Call the predefined methods in the class on the new instances: In the example below, we will apply the sayHello method on the new instances we just created.

     class Person {
         constructor (name, age) {
             this.name = name;
             this.age = age;
         }
         sayHello() {
             return(`Hello, I am ${this.name} and I am ${this.age} years old.`);
         }
     }
    
     const person1 = new Person('Levai', 23);
     const person2 = new person ('Ayo', 30);
    
     person1.sayHello; //This will return 'Hello, I am Levai and I am 23 years old.'
     person2.sayHello; //This will return 'Hello, I am Ayo and I am 30 years old.'
    

Class Inheritance (Optional): You can also create a sub-class from a class. This sub-class will inherit the methods and properties defined in its parent class (the class it is created from), and can be also used to modify the parent class. Additionally, the sub-class can create its own methods and add new properties. When a new instance of the sub-class is created, it will have access to the properties and methods defined in both its parent class and the sub-class. A sub-class can be created from a class using the extends keyword which shows that it inherits all properties and methods defined in it's parent class. In the example below, we will create a sub-class called 'Employee' from the 'Person' class.

class Person {
    constructor (name, age) {
        this.name = name;
        this.age = age;
    }
    sayHello() {
        return(`Hello, I am ${this.name} and I am ${this.age} years old.`);
    }
}

class Employee extends Person {
    constructor(name, age, nationality) {
        super(name, age); // Call the parent class's constructor with super();
        this.nationality = nationality;
    }

    // modify the sayHello method
    sayHello() {
        return(`Hello, I am ${this.name}, I am a ${this.nationality}, and I am ${this.age} years old.`);
    }

    // add a new method
    residence() {
        return(`I am a ${this.nationality} living in Nigeria.`);
    }
}

In the example above, we defined a new property called 'nationality' in the sub-class we created. The sayHello method was also modified to accommodate the new property in the string it returns. Then we went on to add a new method called residence which also returns a string. Again, this.nationality here refers to the property value of the current instance the method is being applied on. In the example below, we will create a new instance of the 'Employee' sub-class, and apply the updated sayHello method and the residence method.

class Person {
    constructor (name, age) {
        this.name = name;
        this.age = age;
    }
    sayHello() {
        return(`Hello, I am ${this.name} and I am ${this.age} years old.`);
    }
}

class Employee extends Person {
    constructor(name, age, nationality) {
        super(name, age); // Call the parent class's constructor with super()
        this.nationality = nationality;
    }

    // modify the sayHello method
    sayHello() {
        return(`Hello, I am ${this.name}, I am a ${this.nationality}, and I am ${this.age} years old.`);
    }

    // add a new method
    residence() {
        return(`I am a ${this.nationality} living in Nigeria.`);
    }
}

const employee1 = new Employee('Ada', 35, 'Nigerian');
employee1.sayHello; //This will return 'Hello, I am Ada, I am a Nigerian, and I am 35 years old.')
employee1.residence; //This will return 'I am a Nigerian living in Nigeria.'

Conclusion

Classes provide us with a way to organize and reuse our code. We can easily create multiple objects with their own unique values from a single template. This makes scaling and maintaining code easier to achieve.