In JavaScript, a constructor function is used to create multiple objects with similar properties and methods. Instead of creating objects manually again and again, we use a constructor to generate them easily.
What is an Object?
An object stores data in key–value pairs.
Example:
let person = {
name: "Harini",
age: 22
};
Here:
- name and age are keys
- "Harini" and 23 are values If we want to create many similar objects, writing this structure repeatedly is not efficient. That’s why we use constructor functions.
What is a Constructor Function?
A constructor function is a normal function used to create objects.
By convention, constructor function names should start with a capital letter.
Example:
function User() {
this.name = "Harini";
}
Here:
- this refers to the newly created object.
- this.name assigns a property to that object.
Creating an Object Using new
To create an object from a constructor, we use the new keyword.
let user1 = new User();
console.log(user1);
What happens when we use new?
When we write new User():
- A new empty object is created.
- this refers to that new object.
- Properties are added to the object.
- The object is returned automatically.
We do not need to manually write return this.
Creating Multiple Objects
Each time we use new, a new object is created.
let user1 = new User();
let user2 = new User();
Both user1 and user2 are separate objects.
Constructor with Arguments
Constructor functions can also accept parameters.
Example:
function User(name) {
this.name = name;
}
let user1 = new User("Harini");
console.log(user1);
Now the value is passed dynamically instead of being hardcoded.
This makes the constructor more flexible.
Adding Properties and Methods
We can add both properties and methods inside a constructor.
Example:
function User(name, age) {
this.name = name;
this.age = age;
this.getAge = function() {
return this.age;
};
}
let user1 = new User("Harini", 22);
console.log(user1.getAge());
Here:
- name and age are properties.
- getAge() is a method.
- Methods are called using parentheses.
Important Points to Remember
- Constructor function names should start with a capital letter.
- Always use the new keyword to create objects.
- this refers to the newly created object.
- Each new call creates a separate object.
Top comments (0)