Constructor Function in JavaScript
A constructor function in JavaScript is a special type of function used to create and initialize
objects. It acts as a blueprint for creating multiple instances of similar objects, each with their
own properties and methods.
Key Characteristics:
Constructor functions are regular functions, but by convention, their names start with a
capital letter to distinguish them from other functions.
They are intended to be called with the new keyword, which triggers special behavior in
JavaScript [1] [2] [3] .
How Constructor Functions Work:
When you invoke a function with the new keyword:
A new empty object is created.
The this keyword inside the function refers to this new object.
Properties and methods are assigned to this.
The new object is returned as the result [1] [2] .
Example:
function Person(name, age) {
[Link] = name;
[Link] = age;
[Link] = function() {
[Link]("Hello, my name is " + [Link]);
};
}
const person1 = new Person("Alice", 30);
const person2 = new Person("Bob", 25);
[Link](); // Hello, my name is Alice
[Link](); // Hello, my name is Bob
In this example, Person is a constructor function. Using new Person(...) creates new objects with
their own name, age, and greet method [3] [1] [2] .
Why Use Constructor Functions?
They allow you to create multiple similar objects efficiently.
Each object created with a constructor function is unique and can have properties added or
changed independently [3] [2] .
Constructor functions can also accept parameters to initialize object properties differently
for each instance.
Constructor Functions vs. Object Literals:
Feature Constructor Function Object Literal
Creates multiple objects Yes No (single object only)
Uses new keyword Yes No
Reusable blueprint Yes No
Example new Person("Alice", 30) { name: "Alice", age: 30 }
Constructor in ES6 Classes:
In ES6, classes use a special constructor method for initialization, but the underlying mechanism
is similar. The constructor method is called automatically when a new instance is created with
new [4] .
Summary:
A constructor function is a pattern for creating multiple object instances with shared
structure and behavior.
Use the new keyword to create objects from a constructor function.
Constructor functions are a fundamental part of object-oriented programming in
JavaScript [3] [1] [2] .
⁂
1. [Link]
2. [Link]
3. [Link]
4. [Link]