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 with the help of that object and object will call the methods of the class as well. We have seen this already when we were reading about Class and Object.

Now, there is one more thing which happens when we create an object of the class, and what is that. 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 automatically 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 parametrized 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 unlike methods and functions
  3. constructor is created inside the class same like methods.
  4. constructor may or maynot have some code written inside it.
class Person {

  constructor() {
    console.log('Constructor is created');
  }
}

let p = new Person();

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, Let’s create some variables and methods inside the class, and let’s see how do these variables and methods work along with a constructor.

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, 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();
  console.log(p.name);
  console.log(p.age);
  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.

Now, there is one thing to notice is that, the

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.
  4. Forth thing to note is that p.name and p.age is also not printing the values that we passed while creating the object of the class.

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 and p.name and p.age is also printing the correct values.

Now, Let’s do one thing that we will create object without any parameters, and then let’s see, how does it work.

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();
   p.name='Jack';
   p.age=20;
  console.log(p.name);
  console.log(p.age);
  p.greet();

So, we can clearly see that we don’t get any error here, and our object without paramters calls the parameterized constructor. So, Javascript is very forgiving language, It doesn’t mind this kind of errors.

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, let’s do one thing, Let’s create a parameteried constructor with house owner, tenant, rent details and then try to execute our code.

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")
    }  
        
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("Rajesh", "Flat No 102, Ganesh Apartments, Ganesh Nagar", "Bangalore", "Karnataka", "Praveen", "Flat No 105, Ganesh Apartments, Ganesh Nagar", "Bangalore", "Karnataka", "January", "15000");
obj.generateRentReceipt();

Now, We have seen that we can simply pass the values of each variables inside the constructor, and we have 2 benefits with that.

  1. We don’t have to create those variables inside the class, which saves our time
  2. We don’t have to assign the values to each variable, we can simply pass the values as an argument in the constructor.

Now, still we have some issues, like we have to still make each variable inside the constructor a class variable, which takes a lot’s of time, so we can simply get rid of that, what we can do is that, we can remove the method generateRentReceipt, and we can print the rent receipt inside the constructor itself.

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, you can see, our code has reduced greatly to some number of lines.

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

Leave a Comment