Advance JavaScript (DOM, BOM, Web API) / Object Oriented Programming

Factory and Constructor Function

✅ Objects

You’ve already learned what an object is and how to create one using the object literal syntax.

An object literal is the simplest way to build an object by directly writing its properties inside curly braces.

Example:

const car = {
  brand: "Honda",
  model: "City",
  start() {
    console.log("Car started");
  }
};

console.log(car.brand); // Honda
car.start(); // Car started

✅ Factory Function

A factory function is a normal function that creates and returns a new object every time it is called. Easy way to create multiple similar objects.

✔️ No class

✔️ No new keyword

✔️ Just a function that produces objects — like a factory!

Simple Example

function createUser(name, age) {
  return {
    name,
    age,
    greet() {
      console.log(`Hi, I'm ${name}`);
    }
  };
}

const user1 = createUser("Bhaskar", 25);
const user2 = createUser("Tisha", 30);

user1.greet(); // Hi, I'm Bhaskar
user2.greet(); // Hi, I'm Tisha

What’s happening?

  • Calling createUser() returns a fresh object

  • Each object has its own properties and methods

  • No need for new

✅ Real World Use Case: Private Data Example (Closure)

function createCounter() {
  let count = 0; // private

  return {
    increment() {
      count++;
      console.log(count);
    }
  };
}

const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2

✅ count cannot be accessed directly — only through methods.


❗️ Constructor Function

A constructor function is a special type of function used to create objects in JavaScript using the new keyword.

✔️ Starts with a capital letter

✔️ Uses this to set properties

✔️ Automatically returns the new object

It’s basically a blueprint for creating multiple similar objects.

Simple Example

function Person(name, age) {
  this.name = name;
  this.age = age;

  this.greet = function () {
    console.log(`Hi, I'm ${this.name}`);
  };
}

const user1 = new Person("Bhaskar", 30);
const user2 = new Person("Tisha", 24);

user1.greet(); // Hi, I'm Bhaskar
user2.greet(); // Hi, I'm Tisha

What’s happening?

  • new Person() creates a new object

  • this.name and this.age assign values to that object

  • No need to write return — JavaScript does it automatically


✅ Constructor vs Factory Function

Constructor Function

Factory Function

Uses new keyword

No new keyword

Uses this

No this required

Auto returns object

Must return object manually

Methods often in prototype (.prototype)

Methods defined inside function