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.
How to create a class and object
- We create a class using a keyword called class.
- class name always starts with upper case letter
When we create a class, then we create some variables inside the class and create some methods inside the class. Let’s understand this with an example
// creating a class
class class_name {
}
// creating object of the class
let obj = new class_name();
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 {
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();
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
- House Owner Name and Address
- Tenant name and Address
- Rent for the Month
- 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.
- House Owner Name and Address – Pradep Yadav, G1-Ganesh Apartment, Test Colony, New Delhi,
- Tenant name and Address – Mahesh Kumar,
- Rent for the Month – June 2023
- 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 " +
+ " 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();
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, you can see clarly, that we didn’t use let keyword for any of the variable inside the class, and w didn’t use function keyword for the method inside the class
But we are getting error when we run this code, and the error is Variable is not defined, and the reason behind that is that the variable is a class variable, and we don’t use let keyword for a class variable, so, when we want to access a class variable value, then we have to access it using this keyword.
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 there is no error after running this code now.
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 we don’t need to write a keyword let, or var before a variable if it is inside the class, and we don’t have to write a keyword function before a method if it is inside the class.
One more thing to note is that, we didn’t see the constructor inside 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.
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.