JS Classes

Classes in JS allow you to group similar functions and data into a single place. Classes essentially allow the bundling of state and behaviour..

The advantages of classes are they encourage reuse ability, this is achieved through creating instances of a class

Defining a class

class Person {
    constructor() {  
    }
}

Creating an instance

const person1 = new Person();
const person2 = new Person;

Constructor function

A class has a constructor function which is a special function that automatically gets called when you create an instance of a class its purpose is to set the initial state (instance variables) of the object

constructor(firstname, lastname) {
    this.firstName = firstname;
    this.lastName = lastname;
}

here the constructor is declaring two parameters when the constructor is called the passed down arguments are assigned accordingly to each of theses parameters.

Instance variables

Instance variables are distinct variables that belong to a specific instance on a class. So when you create an object using the new keyword each instance created has its own instance variables which are under the ownership of that instance. Instance variables are created using the this keyword within a class constructor.

In

Leave a Reply

Your email address will not be published. Required fields are marked *