A constructor function is a regular JavaScript function used to create multiple objects with the same structure.

✔ Acts as a blueprint
✔ Uses the new keyword
✔ Automatically creates and returns an object

1.Why Use Constructor Functions?

Without constructor:

const user1 = { name: "Zaman", age: 25 };
const user2 = { name: "Ahmed", age: 30 };

With constructor:

function User(name, age) {
this.name = name;
this.age = age;
}
const user1 = new User("Zaman", 25);
const user2 = new User("Ahmed", 30); 

✔ Cleaner
✔ Reusable
✔ Scalable

2.Naming Convention

Constructor functions start with a capital letter.

function Car() {}
function Product() {}

3.How new Works (Internals)

When you use new, JavaScript does 4 steps automatically:

function User(name) {
this.name = name;
}
const user = new User("Zaman");

Behind the scenes:

-Creates an empty object {}
-Sets this to the new object
-Links prototype (__proto__)
-Returns the object automatically

Equivalent to:

const user = {};
user.__proto__ = User.prototype;
User.call(user, "Zaman");

4.Adding Methods to Constructor

❌ Bad Practice (creates new method per object)

function User(name) {
this.name = name;
this.greet = function () {
console.log("Hello");
};
}

✅ Best Practice (use prototype)

function User(name) {
this.name = name;
}User.prototype.greet = function () {
console.log(`Hello ${this.name}`);
};

 

✔ Memory efficient
✔ Shared method

5.Using this in Constructor

function Product(name, price) {
this.name = name;
this.price = price;
}

this refers to the newly created object

6.instanceof Operator

Checks object relationship.

user instanceof User; // true

7.Return Value in Constructor

function Test() {
this.x = 10;
return { y: 20 };
}new Test(); // { y: 20 }

⚠️ If you return an object → overrides this
✔ If return primitive → ignored

8.Constructor vs Factory Function

Constructor

function User(name) {
this.name = name;
}
const u = new User("Zaman");

Factory

function createUser(name) {
return { name };
}

Categorized in:

Javascript,