-
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 similar objects efficiently. Instead of manually defining each object with the same structure, constructors allow you to define a blueprint that can be used to generate new objects with shared properties and methods. Understanding constructors is essential for object-oriented programming in JavaScript and for building scalable and maintainable applications.
In this tutorial, you will learn what object constructors are, how to use them, practical examples, common mistakes, best practices, and real-world applications.
Object constructors are important because they:
Allow the creation of multiple objects with similar structure
Enable reusable code and avoid repetition
Support object-oriented programming principles
Allow initialization of properties at the time of object creation
Facilitate the use of methods that are shared across objects
Without constructors, developers would have to manually create multiple objects, leading to repetitive code and higher chances of errors.
A constructor is a regular function, but by convention, its name starts with a capital letter. When called with the new keyword, it creates a new object with this pointing to that new object. Properties and methods can then be assigned to this inside the constructor.
function Student(name, age, course) {
this.name = name;
this.age = age;
this.course = course;
}
Once a constructor is defined, you can create objects using the new keyword:
const student1 = new Student("Aarushi", 20, "JavaScript");
const student2 = new Student("Priya", 22, "React");
console.log(student1.name); // Aarushi
console.log(student2.course); // React
Each object has its own set of properties, but they all share the same constructor structure.
Methods can be added inside the constructor, but it is more efficient to add them to the constructor’s prototype so that all objects share the same function rather than creating a new function for each object.
function Student(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log("Hello, my name is " + this.name);
};
}
const student = new Student("Saanvi", 21);
student.greet(); // Hello, my name is Saanvi
While this works, each object has its own copy of the greet function, which can be memory inefficient.
function Student(name, age) {
this.name = name;
this.age = age;
}
Student.prototype.greet = function() {
console.log("Hello, my name is " + this.name);
};
const student1 = new Student("Isha", 20);
const student2 = new Student("Priya", 22);
student1.greet(); // Hello, my name is Isha
student2.greet(); // Hello, my name is Priya
Using prototypes ensures that all objects created from the constructor share the same method, saving memory and maintaining consistency.
Constructors can accept parameters to initialize object properties dynamically:
function Course(title, duration) {
this.title = title;
this.duration = duration;
}
const course1 = new Course("JavaScript Basics", "4 weeks");
const course2 = new Course("React Advanced", "6 weeks");
console.log(course1.title); // JavaScript Basics
console.log(course2.duration); // 6 weeks
This flexibility makes constructors ideal for creating multiple objects with similar properties but different values.
You can implement inheritance by calling one constructor from another using call() or by setting the prototype.
function Person(name) {
this.name = name;
}
function Teacher(name, subject) {
Person.call(this, name);
this.subject = subject;
}
Teacher.prototype = Object.create(Person.prototype);
Teacher.prototype.constructor = Teacher;
const teacher = new Teacher("Saanvi", "Math");
console.log(teacher.name); // Saanvi
console.log(teacher.subject); // Math
This allows the Teacher constructor to inherit properties from Person while adding its own properties.
Forgetting to use the new keyword, which causes this to refer to the global object
Adding methods inside the constructor instead of using the prototype, leading to memory inefficiency
Not capitalizing the constructor function name, which is a convention for readability
Overwriting the prototype incorrectly, which can break the constructor reference
Using constructors unnecessarily when object literals would suffice
Always capitalize constructor function names for clarity
Use prototypes for shared methods to optimize memory usage
Pass parameters to constructors to initialize objects dynamically
Use inheritance properly to extend functionality
Avoid using constructors for single, simple objects—object literals are sufficient in such cases
Object constructors are commonly used in:
Creating multiple user or student objects in applications
Modeling real-world entities like courses, books, or products
Implementing object-oriented design patterns
Building libraries or frameworks with reusable components
Managing application data in structured objects
function Student(name, age, course) {
this.name = name;
this.age = age;
this.course = course;
}
const student1 = new Student("Aarushi", 20, "JavaScript");
const student2 = new Student("Priya", 22, "React");
console.log(student1.name); // Aarushi
console.log(student2.course); // React
Student.prototype.greet = function() {
console.log("Hello, my name is " + this.name);
};
student1.greet(); // Hello, my name is Aarushi
student2.greet(); // Hello, my name is Priya
function Course(title, duration) {
this.title = title;
this.duration = duration;
}
Course.prototype.info = function() {
console.log(this.title + " lasts " + this.duration);
};
const course1 = new Course("JavaScript Basics", "4 weeks");
course1.info(); // JavaScript Basics lasts 4 weeks
function Person(name) {
this.name = name;
}
function Teacher(name, subject) {
Person.call(this, name);
this.subject = subject;
}
Teacher.prototype = Object.create(Person.prototype);
Teacher.prototype.constructor = Teacher;
Teacher.prototype.introduce = function() {
console.log("I am " + this.name + ", teaching " + this.subject);
};
const teacher = new Teacher("Saanvi", "Math");
teacher.introduce(); // I am Saanvi, teaching Math
JavaScript object constructors provide a powerful way to create multiple objects with similar structures. They support dynamic initialization, reusable methods via prototypes, and object-oriented patterns such as inheritance. Proper use of constructors allows developers to write maintainable, scalable, and efficient code while avoiding repetition and memory issues. Mastering constructors is crucial for building professional JavaScript applications and understanding object-oriented programming concepts 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
