Objects, Classes and Constructor in Javascript

Objects, Classes and Constructor in Javascript

Classes and Objects

A class in any programming language is a template or a blueprint of a real time object. An Object is an implementation of the class. So, we can see that the class and object both are related to each other, We can not have an object without a class or a class without an object.

We will discuss more about class and object in Javascript but, Let’s see how can we create a class and object in Javascript.

How to create a class and object

  1. We create a class using a keyword called class.
  2. class name always starts with upper case letter
  3. object of a class is created outside the class.
  4. object is a kind of variable, So, we create an object using let keyword.
  5. We have to use new keyword as well for creating an object of a class.
// creating a class

class class_name {
  
}

// creating object of the class

let obj = new class_name();

So, you can see, how a class and an object of a class is created in Javascript.

When we create a class, then we create some variables inside the class and create some methods inside the class as well. Let’s understand this with an example

Methods and Variables inside a class

So, In the above code, we have seen, how we can create a class, and can we create object of that class. Now, Let’s see what can we have inside a class, So, we can have variables and methods inside a class. Let’s see how can we accomodate a variable and a method inside a class.

class class_name {

let variable_name = variable_value;

 function method_name() {
    // some code
  }
  
}

let obj = new class_name();
obj.variable_name;
obj.method_name();

Now, if you see properly, then you see that we get an error when we use let keyword for a variable inside a class and we get an error when we use function keyword for a method inside a class, so this is the first thing to remember we don’t use any keyword for a variable or a method inside the class. Now, let’s see how should we write them.

class class_name {

variable_name = variable_value;

method_name() {
    // some code
  }
  
}

let obj = new class_name();
obj.variable_name;
obj.method_name();

Now, this was a syntax of a class with variables and methods, and how we can access those methods and variables using the object of the class. Let’s see the example for the same.

Let’s create a class with name “Person”, where we have some variables “name” and “age” and a method “greet”.

class Person {
 name = 'John';
 age = 20;

 greet() {
   console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  };
}
  let p = new Person();
  console.log(p.name);
  console.log(p.age);
  p.greet();

Now, there is a problem with the above code that we are assigning the values to the variables while declaring them in the class but ideally, we should assign values to the variables using the object.

class Person {
 name = '';
 age = '';

 greet() {
   console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  };
}
  let p = new Person();
  p.name = 'John';
  p.age = 30;
  console.log(p.name);
  console.log(p.age);
  p.greet();

So, we are using this.name and this.age in the method to access the values of name and age, and it has to be understood well, that if we don’t use this keyword, then we are going to get an error because these are the variables inside a class. Let’s try that.

class Person {
 name = 'John';
 age = 20;

 greet() {
   console.log(`Hello, my name is ${name} and I am ${age} years old.`);
  };
}
  let p = new Person();
  console.log(p.name);
  console.log(p.age);
  p.greet();

Real Time Example of a class and Object

Let’s take a real time example of rent receipt.

The Template of the rent reciept is similar to a class, because we can write any name and values there and when we fill the rent receipt, then it becomes an object, because now the rent receipt belongs to a single person, no one else can own it. Earlier, when, nothing was written on the rent receipt, that was just a format, no one has owned it, but once the information is filled, then that’s it, now it becomes an object.

So, a Rent Receipt will have below fields

  1. House Owner Name and Address
  2. Tenant name and Address
  3. Rent for the Month
  4. Rent Amount

So, when all these fields are filled, then this belongs to the Owner and Tenant.

Now, if we have to create a class for a Rent Receipt, We must have these variables in our class, so that when we create an object, then object can assign values to these variables.

  1. House Owner Name and Address – Pradep Yadav, G1-Ganesh Apartment, Test Colony, New Delhi,
  2. Tenant name and Address – Mahesh Kumar,
  3. Rent for the Month – June 2023
  4. Rent Amount – 15000 INR

So, with this example, it is quite clear, that the class is just a template and object is the implementation of the template i.e. class.

Let’s crate a class for Rent Receipt, and let’s have a method inside it for generating Rent Receipt. One thing to note is that we never use any let, var or const keyword for a variable inside a class and we never use function keyword for method inside a class. If we do that, we are going to get error.

class RentalReceipt {

  generateRentReceipt() {
    console.log("Rent Receipt is generated and rent Received by the House Owner Rajesh and the House Owner Address is: Flat No 102, Ganesh Apartments, Ganesh Nagar, Bangalore, Karnataka and rent paid by the Tenant Praveen and the Tenant Address : Flat No 105, Ganesh Apartments, Ganesh Nagar, Bangalore, Karnataka  and the Rent Month: January and Rent Amount: 15000");
  }
  
}

let obj = new RentalReceipt();
obj.generateRentReceipt();

Now, there is a problem with the above code, that we have harcoded the values, and if we want to print this receipt for a different owner and tenant, then we have to write the same code again, and we don’t want it like this. We want to define the class only once and then we just want to assign values to the object. So, Let’s create a class something like this

class RentalReceipt {

  houseOwnerName = "";
  houseOwnerAddressLine1 = "";
  houseOwnerAddressCity = "";
  houseOwnerAddressState = "";
  tenantname = "";
  tenantAddressLine1 = "";
  tenantAddressCity = "";
  tenantAddressState = "";
  RentMonth = "";
  RentAmount = 0;

  generateRentReceipt() {
    console.log("Rent Receipt is generated and rent Received by the House Owner " + this.houseOwnerName + " and the House Owner Address is: " + this.houseOwnerAddressLine1 + ", " + this.houseOwnerAddressCity + ", " + this.houseOwnerAddressState 
 + " and rent paid by the Tenant : " + this.tenantname + " and the Tenant Address : " + this.tenantAddressLine1 + ", " + this.tenantAddressCity + ", " + this.tenantAddressState + "  and the Rent Month: " + this.RentMonth + " and Rent Amount: " + this.RentAmount);
  }
  
}

let obj = new RentalReceipt();
obj.houseOwnerName = "Rajesh";
obj.houseOwnerAddressLine1 = "Flat No 102, Ganesh Apartments, Ganesh Nagar";
obj.houseOwnerAddressCity = "Bangalore";
obj.houseOwnerAddressState = "Karnataka";
obj.tenantname = "Praveen";
obj.tenantAddressLine1 = "Flat No 105, Ganesh Apartments, Ganesh Nagar";
obj.tenantAddressCity = "Bangalore";
obj.tenantAddressState = "Karnataka";
obj.RentMonth = "January";
obj.RentAmount = "15000";
obj.generateRentReceipt();

So, we can see, that now, we are using the variables, so we can reuse the same code and class for different object as well.

Constructor

When we create object of the class, then we assign values to the variables of the class and object will call the methods. When we create an object of the class, then the constructor of the class gets executed by default and class gets instantiated. Now, Let’s see, what is a constructor.

  • Constructor is a special type of method, which gets created as soon as we create a class by default.
  • This constructor is called a default constructor.
  • This default constructor is a hidden constructor, and we can not see it.
  • Default constructor doesn’t have any parameter
  • Constructor gets executed as soon as we create object of the class.
  • Constructors can not be executed explicitly.
  • We can create a constructor with parameters as well, and this is called Paramtersed constructor.

Let’s create a class, and understand the concept of class, objects and constructor.

Now, you can see in the above example, that we created a class and we created some variables and methods inside the class, then we created an object of that class and the object has called all the variables and the method of the class. One thing to note is that the constructor of the class get executed as soon as the object of the class is created.

One more thing to note is that, we didn’t see the constructor inside the class and we know that the constructor is created by default as soon as a class is created, So where is the constructor, So constructor is hidden, but if we want to see the constructor, we can create it ourself. So, let’s do that.

How to create a Constructor of the class

  1. We need to use constructor keyword for creating a constructor.
  2. constructor doesn’t have any name
  3. constructor is created inside the class.
  4. constructor may or maynot have some code written inside it.
class Person {

constructor() {
   console.log("constructor is created");
}

 name = 'John';
 age = 20;

 greet() {
   console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  };
}
  let p = new Person();
  console.log(p.name);
  console.log(p.age);
  p.greet();

Now, you can see in the above code, that we have created a constructor but we didn’t execute the constructor but the constructor got executed by default as soon as the object of the class is created. Now, this was a default constructor.

Let’s see the example of a paramterized constructor as well.

class Person {

constructor() {
    console.log("default constructor is created");
}

constructor(name, age) {
   console.log("parameterized constructor is created");
}

 greet() {
   console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  };
}
  let p = new Person('Jack', 35);
  p.greet();

Now, we are getting an error with the above code that we can have only one constructor in a class in Javascript. So, let’s remove the default constructor from our code and only have the parameterized constructor in the class.

class Person {

constructor(name, age) {
   console.log("parameterized constructor is created");
}

 greet() {
   console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  };
}
  let p = new Person('Jack', 35);
  p.greet();
  1. Now, when we run this type of code, then one thing to note is that when we create the object of the class, then we have to pass the same number of paramters that we have in our constructor inside the class.
  2. Second thing to note is that we don’t have to declare variables in the class seperately, We can have them as a parameter in the constructor.
  3. Third thing to note is that the paramters of the constructor are not the variables of the class, so that’s why the greet method is printing undefined instead of printing name as Jack and age as 35.

So, we will have to make the variables as class variables, and we can do it something like this.

class Person {

constructor(name, age) {
   console.log("parameterized constructor is created");
   this.name = name;
   this.age = age;
}


 greet() {
   console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  };
}
  let p = new Person('Jack', 35);
  p.greet();

Now, we see that the greet method is printing the correct statement. Now, If I don’t want the greet method and I want to print the statement without greet method, then we can do that as well. We can print the statement inside the constructor as well, and if we do that we don’t have to write this.name, we can directly write name and age in the statement. Let’s do that.

class Person {

constructor(name, age) {
   console.log("parameterized constructor is created");
   console.log(`Hello, my name is ${name} and I am ${age} years old.`);
}


}
  let p = new Person('Jack', 35);

Now, no need to call any method or variable, just create object of the class and everything is done.

Let’s see the same example with Rent Receipt as well.

class RentalReceipt {

constructor() {
console.log("constructor is called");
}

  houseOwnerName = "";
  houseOwnerAddressLine1 = "";
  houseOwnerAddressCity = "";
  houseOwnerAddressState = "";
  tenantname = "";
  tenantAddressLine1 = "";
  tenantAddressCity = "";
  tenantAddressState = "";
  RentMonth = "";
  RentAmount = 0;

  generateRentReceipt() {
    console.log("Rent Receipt is generated and rent Received by the House Owner " + this.houseOwnerName + " and the House Owner Address is: " + this.houseOwnerAddressLine1 + ", " + this.houseOwnerAddressCity + ", " + this.houseOwnerAddressState 
 + " and rent paid by the Tenant : " + this.tenantname + " and the Tenant Address : " + this.tenantAddressLine1 + ", " + this.tenantAddressCity + ", " + this.tenantAddressState + "  and the Rent Month: " + this.RentMonth + " and Rent Amount: " + this.RentAmount);
  }
  
}

let obj = new RentalReceipt();
obj.houseOwnerName = "Rajesh";
obj.houseOwnerAddressLine1 = "Flat No 102, Ganesh Apartments, Ganesh Nagar";
obj.houseOwnerAddressCity = "Bangalore";
obj.houseOwnerAddressState = "Karnataka";
obj.tenantname = "Praveen";
obj.tenantAddressLine1 = "Flat No 105, Ganesh Apartments, Ganesh Nagar";
obj.tenantAddressCity = "Bangalore";
obj.tenantAddressState = "Karnataka";
obj.RentMonth = "January";
obj.RentAmount = "15000";
obj.generateRentReceipt();

Now, if you see that the assigning values to object is a tedious task, and we need to assign these values to every object we create, and then we need to call the method generateReceipt for each Object, So can we do something else, so that the line of code will be reduced and it will become more reusable. Let’s try it.

class RentalReceipt {

  constructor() {
    console.log("Default Constructor is executed")
  }


  constructor(houseOwnerName, houseOwnerAddressLine1, houseOwnerAddressCity,houseOwnerAddressState, tenantname, tenantAddressLine1, tenantAddressCity, tenantAddressState, RentMonth, RentAmount) {

    console.log("Parameterised Constructor is executed")
    
        console.log("Rent Receipt is generated and rent Received by the House Owner " + this.houseOwnerName + " and the House Owner Address is: " + this.houseOwnerAddressLine1 + ", " + this.houseOwnerAddressCity + ", " + this.houseOwnerAddressState 
     + " and rent paid by the Tenant : " + this.tenantname + " and the Tenant Address : " + this.tenantAddressLine1 + ", " + this.tenantAddressCity + ", " + this.tenantAddressState + "  and the Rent Month: " + this.RentMonth + " and Rent Amount: " + this.RentAmount);
  }
  
}

let obj = new RentalReceipt("Rajesh", "Flat No 102, Ganesh Apartments, Ganesh Nagar", "Bangalore", "Karnataka", "Praveen", "Flat No 105, Ganesh Apartments, Ganesh Nagar", "Bangalore", "Karnataka", "January", "15000");

You will get an error when you will run this code that a class can have only 1 Constructor, So you will have to remove the default constructor from the class.

class RentalReceipt {


  constructor(houseOwnerName, houseOwnerAddressLine1, houseOwnerAddressCity,houseOwnerAddressState, tenantname, tenantAddressLine1, tenantAddressCity, tenantAddressState, RentMonth, RentAmount) {
    

    console.log("Parameterised Constructor is executed")
    
        console.log("Rent Receipt is generated and rent Received by the House Owner " + houseOwnerName + " and the House Owner Address is: " + houseOwnerAddressLine1 + ", " + houseOwnerAddressCity + ", " + houseOwnerAddressState 
     + " and rent paid by the Tenant : " + tenantname + " and the Tenant Address : " + tenantAddressLine1 + ", " + tenantAddressCity + ", " + tenantAddressState + "  and the Rent Month: " + RentMonth + " and Rent Amount: " + RentAmount);
  }
  
}

let obj = new RentalReceipt("Rajesh", "Flat No 102, Ganesh Apartments, Ganesh Nagar", "Bangalore", "Karnataka", "Praveen", "Flat No 105, Ganesh Apartments, Ganesh Nagar", "Bangalore", "Karnataka", "January", "15000");

Now, if you run the code, you won’t get any error but you will se that the console.log statement is not printing the values correctly. It is printing undefined in place of values.

class RentalReceipt {


  constructor(houseOwnerName, houseOwnerAddressLine1, houseOwnerAddressCity,houseOwnerAddressState, tenantname, tenantAddressLine1, tenantAddressCity, tenantAddressState, RentMonth, RentAmount) {
    this.houseOwnerName = houseOwnerName;
    this.houseOwnerAddressLine1 = houseOwnerAddressLine1;
    this.houseOwnerAddressCity = houseOwnerAddressCity;
    this.houseOwnerAddressState = houseOwnerAddressState;
    this.tenantname = tenantname;
    this.tenantAddressLine1 = tenantAddressLine1;
    this.tenantAddressCity = tenantAddressCity;
    this.tenantAddressState = tenantAddressState;
    this.RentMonth = RentMonth;
    this.RentAmount = RentAmount;
    

    console.log("Parameterised Constructor is executed")
    
        console.log("Rent Receipt is generated and rent Received by the House Owner " + this.houseOwnerName + " and the House Owner Address is: " + this.houseOwnerAddressLine1 + ", " + this.houseOwnerAddressCity + ", " + this.houseOwnerAddressState 
     + " and rent paid by the Tenant : " + this.tenantname + " and the Tenant Address : " + this.tenantAddressLine1 + ", " + this.tenantAddressCity + ", " + this.tenantAddressState + "  and the Rent Month: " + this.RentMonth + " and Rent Amount: " + this.RentAmount);
  }
  
}

let obj = new RentalReceipt("Rajesh", "Flat No 102, Ganesh Apartments, Ganesh Nagar", "Bangalore", "Karnataka", "Praveen", "Flat No 105, Ganesh Apartments, Ganesh Nagar", "Bangalore", "Karnataka", "January", "15000");

Now, we can see that our code is working perfectly fine. So, this was all about classes, objects and constructors.

Leave a Comment