-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
In JavaScript, object constructors are special functions used to create multiple objects with the same structure and properties. Instead of manually creating objects one by one, constructors allow developers to define a blueprint for objects and instantiate new objects efficiently.
Constructors are especially useful when building applications with many similar objects, like users, products, or students. They also introduce the concept of prototypes, enabling shared methods across instances.
An object constructor is simply a function designed to create objects. By convention, constructor function names start with an uppercase letter.
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
this
refers to the new object being created.
Each time the constructor is called with new
, a new object instance is created.
You create objects using the new
keyword:
const person1 = new Person("John", "Doe", 25);
const person2 = new Person("Alice", "Smith", 30);
console.log(person1.firstName); // John
console.log(person2.age); // 30
person1
and person2
are separate instances.
Each has its own copy of properties.
You can define methods inside constructors.
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.fullName = function() {
return this.firstName + " " + this.lastName;
};
}
const person = new Person("John", "Doe", 25);
console.log(person.fullName()); // John Doe
Note: Methods defined inside the constructor are duplicated for each object, which may use more memory for many instances.
To save memory, you can add methods to the constructor’s prototype so all instances share the same method:
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
// Add method to prototype
Person.prototype.fullName = function() {
return this.firstName + " " + this.lastName;
};
const person1 = new Person("John", "Doe", 25);
const person2 = new Person("Alice", "Smith", 30);
console.log(person1.fullName()); // John Doe
console.log(person2.fullName()); // Alice Smith
Prototype methods are shared, so memory usage is reduced.
This is a key concept in JavaScript object-oriented programming.
You can assign default values to properties in the constructor:
function Person(firstName, lastName, age = 18) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
const person = new Person("John", "Doe");
console.log(person.age); // 18
Default values ensure that the object has valid properties even if some arguments are missing.
Objects created with a constructor can be checked using instanceof
:
console.log(person instanceof Person); // true
console.log(person instanceof Object); // true
instanceof
confirms that an object was created from a specific constructor.
Feature | Object Literal | Constructor Function |
---|---|---|
Creation | const obj = {} |
const obj = new Constructor() |
Multiple Instances | Manual duplication required | Easily create many instances |
Shared Methods | Must define separately | Use prototype for shared methods |
Dynamic Properties | Can assign individually | Set via constructor parameters |
Constructor functions make objects dynamic by using parameters:
function Product(name, price, quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
this.totalCost = function() {
return this.price * this.quantity;
};
}
const product1 = new Product("Laptop", 500, 2);
const product2 = new Product("Phone", 300, 5);
console.log(product1.totalCost()); // 1000
console.log(product2.totalCost()); // 1500
Each instance has its own properties while sharing the same structure.
Constructor function names should start with uppercase letters.
Use prototype for methods that do not need to be unique per instance.
Always use new
when calling a constructor; otherwise, this
refers to the global object, causing errors.
Constructors are foundational for object-oriented JavaScript and class-based ES6 syntax.
Object constructors are functions used as blueprints to create objects with the same structure.
Use the new
keyword to instantiate objects.
Methods can be defined inside the constructor (per instance) or on prototype (shared).
Default values, dynamic parameters, and instanceof
checks make constructors flexible and robust.
Constructors help avoid repetitive object creation and form the base for modern classes in JavaScript.
Basic Constructor
Create a constructor Person
with firstName
, lastName
, and age
properties. Instantiate two objects and log their full details.
Method Inside Constructor
Add a method fullName()
inside the Person
constructor that returns the full name. Create an object and call this method.
Prototype Method
Move the fullName()
method to the constructor's prototype and demonstrate that both instances can access it.
Default Parameters
Modify the Person
constructor to set a default age
of 18 if no age is provided. Create an object without passing age and log it.
Multiple Instances
Create a Product
constructor with name
, price
, and quantity
. Instantiate three different products and log their properties.
Dynamic Method Using Parameters
Add a method totalCost()
in the Product
constructor to calculate price * quantity
. Call this method for each product.
Checking Constructor
Use instanceof
to check if an object created with Person
is actually an instance of Person
and Object
.
Incorrect Use of new
Call the Person
constructor without new
and explain the difference in behavior.
Nested Objects in Constructor
Create a Student
constructor with a nested object marks
containing math
and science
scores. Instantiate a student and log the marks.
Adding Prototype Property
Add a shared property species = "Homo sapiens"
to the Person
prototype. Log this property from multiple instances to show it is shared.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts