One of the biggest advantages of JavaScript is the ability to create multiple objects with similar properties and behaviors. Writing each object manually becomes repetitive and inefficient.
To solve this problem, JavaScript provides Constructor Functions.
What is a Constructor in JavaScript?
A constructor is a special function used to create and initialize objects.
Think of it as a blueprint or template for creating multiple objects with similar properties.
Definition
A Constructor Function is a function used with the
newkeyword to create objects.
Why Do We Need Constructors?
Suppose we want to create three students.
Without constructors:
const student1 = {
name: "John",
age: 21,
city: "Chennai"
};
const student2 = {
name: "David",
age: 22,
city: "Madurai"
};
const student3 = {
name: "Sam",
age: 20,
city: "Coimbatore"
};
This approach works, but it involves repeating code.
With Constructor
function Student(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
}
const student1 = new Student("John", 21, "Chennai");
const student2 = new Student("David", 22, "Madurai");
const student3 = new Student("Sam", 20, "Coimbatore");
Much cleaner and reusable.
Real-Life Example
Imagine a cookie cutter.
One mold can produce many cookies.
Cookie Mold
↓
Cookie 1
Cookie 2
Cookie 3
Cookie 4
Similarly,
Constructor
↓
Object 1
Object 2
Object 3
Syntax of Constructor Function
function Person(name, age) {
this.name = name;
this.age = age;
}
Creating objects:
const p1 = new Person("John", 25);
const p2 = new Person("David", 30);
Understanding this
Inside a constructor, this refers to the object being created.
function Employee(name, salary) {
this.name = name;
this.salary = salary;
}
Creating object:
const emp1 = new Employee("John", 50000);
Object created:
{
name: "John",
salary: 50000
}
Real-Life Example of this
Suppose a teacher says:
"My classroom"
"My" refers to that teacher.
Similarly,
this.name
means
Current object's name
Creating Multiple Objects
function Car(brand, color, price) {
this.brand = brand;
this.color = color;
this.price = price;
}
const car1 = new Car("BMW", "Black", 6000000);
const car2 = new Car("Audi", "White", 7000000);
const car3 = new Car("Benz", "Silver", 8000000);
console.log(car1);
console.log(car2);
console.log(car3);
Output:
{
brand: "BMW",
color: "Black",
price: 6000000
}
{
brand: "Audi",
color: "White",
price: 7000000
}
{
brand: "Benz",
color: "Silver",
price: 8000000
}
How Does the new Keyword Work?
When we write:
const emp = new Employee("John", 50000);
JavaScript performs four steps.
Step 1: Creates an Empty Object
{}
Step 2: this Points to That Object
this = {}
Step 3: Properties Are Added
{
name: "John",
salary: 50000
}
Step 4: Object Is Returned
const emp = {
name: "John",
salary: 50000
};
Visual Representation
new Employee("John",50000)
↓
Creates Empty Object
↓
this.name = "John"
this.salary = 50000
↓
Returns Object
↓
{
name:"John",
salary:50000
}
Adding Methods to Constructor
Methods can also be included.
function Student(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log("Hello " + this.name);
};
}
const s1 = new Student("John", 21);
s1.greet();
Output
Hello John
Real-Life Example
Car
Properties:
Brand
Color
Price
Actions:
Start()
Stop()
Accelerate()
Actions are methods.
Example with Laptop
function Laptop(brand, ram, processor) {
this.brand = brand;
this.ram = ram;
this.processor = processor;
this.showDetails = function() {
console.log(
this.brand,
this.ram,
this.processor
);
};
}
const laptop1 =
new Laptop("HP", "16GB", "i7");
laptop1.showDetails();
Output
HP 16GB i7
Constructor Naming Convention
Constructor names usually start with a capital letter.
Example:
function Student() {}
function Employee() {}
function Car() {}
Not recommended:
function student() {}
Capital letters indicate that the function is intended to be used with new.
Constructor with Default Values
function Mobile(
brand = "Samsung",
price = 30000
) {
this.brand = brand;
this.price = price;
}
const m1 = new Mobile();
console.log(m1);
Output
{
brand: "Samsung",
price: 30000
}
Constructor for Employee
function Employee(id, name, salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
const emp1 =
new Employee(101, "John", 50000);
const emp2 =
new Employee(102, "David", 60000);
console.log(emp1);
console.log(emp2);
Constructor for Product
function Product(name, price) {
this.name = name;
this.price = price;
}
const p1 =
new Product("Laptop", 70000);
const p2 =
new Product("Mobile", 40000);
Constructor for Animal
function Animal(name, type) {
this.name = name;
this.type = type;
}
const dog =
new Animal("Tommy", "Dog");
console.log(dog);
Output
{
name:"Tommy",
type:"Dog"
}
Built-in Constructors
JavaScript provides several built-in constructors.
String
const name = new String("John");
Number
const age = new Number(25);
Boolean
const status = new Boolean(true);
Array
const numbers = new Array(10,20,30);
Object
const obj = new Object();
Date
const today = new Date();
Constructor Function vs Object Literal
Object Literal
const student = {
name: "John",
age: 21
};
Suitable for one object.
Constructor
function Student(name, age) {
this.name = name;
this.age = age;
}
const s1 = new Student("John", 21);
const s2 = new Student("David", 22);
Suitable for multiple objects.
| Object Literal | Constructor Function |
|---|---|
| Single object | Multiple objects |
| Simple | Reusable |
| Less code for one object | Less repetition |
| No blueprint | Blueprint approach |
Constructor Function vs Factory Function
Factory Function
function createStudent(name, age) {
return {
name,
age
};
}
const s1 =
createStudent("John", 21);
Constructor Function
function Student(name, age) {
this.name = name;
this.age = age;
}
const s1 =
new Student("John", 21);
| Factory Function | Constructor Function |
|---|---|
| Uses return | Uses new
|
No this
|
Uses this
|
| Creates objects | Creates objects |
| Easier to understand | Traditional approach |
What Happens Without new?
function Student(name) {
this.name = name;
}
const s1 = Student("John");
Without new, the function behaves like a normal function and may cause unexpected results.
Always write:
const s1 =
new Student("John");
Real-World Analogy
Think about a university.
Blueprint
Student Form
Contains:
- Name
- Age
- Department
Using that form:
Student 1
Student 2
Student 3
Student 4
The form is the constructor.
Each student is an object.
References :
https://www.w3schools.com/js/js_object_constructors.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor
Top comments (0)