惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
宝玉的分享
宝玉的分享
月光博客
月光博客
小众软件
小众软件
Jina AI
Jina AI
WordPress大学
WordPress大学
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
Tailwind CSS Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 【当耐特】
博客园 - 三生石上(FineUI控件)
博客园 - 司徒正美
大猫的无限游戏
大猫的无限游戏
The Cloudflare Blog
G
Google Developers Blog
M
MIT News - Artificial intelligence
N
Netflix TechBlog - Medium
云风的 BLOG
云风的 BLOG
MyScale Blog
MyScale Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
爱范儿
爱范儿
U
Unit 42
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Blog — PlanetScale
Blog — PlanetScale

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Constructor in JavaScript
Annapoorani Kadhiravan · 2026-06-20 · via DEV Community
Cover image for Constructor in JavaScript

Annapoorani Kadhiravan

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 new keyword 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