- JS Introduction
- JS Introduction
- JS Comments
- JS Variables
- JS Datatypes
- JS Operators
- JS Type Conversions
- JS Control Flow
- JS Comparisons
- JS If else
- JS If else Ladder
- JS Ternary Operator
- JS Switch
- JS For Loop
- JS For In
- JS For Of
- JS While
- JS Do While
- JS Break & Continue
- JS Functions
- JS Function Declaration
- JS Function Parameters
- JS Return Statement
- JS Function Expressions
- JS Anonymous Functions
- JS Objects
- JS Objects
- JS Object Methods
- JS Object Constructors
- JS Object Destructuring
- JS Object Prototypes
- JS Map, Filter & Reduce
- JS ES6
- JS ES6
- JS let and const
- JS Arrow Functions
- JS Template Literals
- Destructuring Assignment
- JS Spread Operator
- JS Default Parameters
- JS Classes
- JS Inheritance
- JS Map
- JS Set
- JS Async
- JS Callbacks
- JS Asynchronous
- JS Promises
- JS Async/Await
- JS HTML DOM/BOM
- JS Document Object
- JS getElementbyId
- getElementsByClassName
- JS getElementsByName
- getElementsByTagName
- JS innerHTML
- JS outerHTML
- JS Window Object
- JS History Object
- JS Navigator Object
- JS Screen Object
JavaScript Object Constructor
- An object constructor is a special function used as a blueprint to create and initialize multiple objects of the same type.
- It defines a template, ensuring that every object created from it shares the same properties and methods, but with unique data.
When you are building an application, you often need to create many objects of the same "kind"—like multiple users, products in a shopping cart, or characters in a game. Instead of manually typing out each object literal, you use a constructor to automate the process.
Syntax:
function ObjectName(property1, property2, /* ... */) {
this.property1 = property1;
this.property2 = property2;
// ...
this.methodName = function(/* ... */) {
// Code to be executed
};
}
- ObjectName: The name of the constructor. By convention, it starts with an uppercase letter (PascalCase).
- property1, property2, ...: Parameters that act as placeholders for the data you'll pass in when creating a new object.
- this keyword: In a constructor,
thisrefers to the new object being created. It "binds" the values to that specific instance. - methodName: A function attached to the object, allowing instances to perform actions.
User instead of user). This signals to other developers that the function is intended to be called with the new keyword.
Why it is Used:
- Object Initialization: It streamlines the process of setting up an object's initial state. You don't have to worry about forgetting a property.
- Code Reusability: You write the logic once in the constructor and can spin up hundreds of unique instances without repeating yourself.
- Consistency: It ensures that every object of a certain type has the same "shape," which makes your code more predictable and easier to debug.
new keyword, this will not point to a new object. In non-strict mode, it will point to the global window object, which can cause serious bugs by overwriting global variables.
Example:
Imagine you are building a dealership management system. You need a way to quickly catalog different vehicles.
// Object Constructor Function for Cars
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.displayInfo = function() {
console.log(`Make: ${this.make}, Model: ${this.model}, Year: ${this.year}`);
};
}
// Creating Instances of the Car Object using 'new'
const car1 = new Car('Toyota', 'Camry', 2022);
const car2 = new Car('Honda', 'Accord', 2021);
// Calling Object Methods
car1.displayInfo(); // Output: Make: Toyota, Model: Camry, Year: 2022
car2.displayInfo(); // Output: Make: Honda, Model: Accord, Year: 2021
Object Constructor with Prototypes: To improve memory efficiency, you can define methods on the object's prototype.
When you define a method inside the constructor (like displayInfo in the example above), a new copy of that function is created for every single object. If you have 1,000 cars, you have 1,000 copies of the same function in memory. Using prototypes solves this.
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
// Adding a Method to the Object's Prototype
Car.prototype.displayInfo = function() {
console.log(`Make: ${this.make}, Model: ${this.model}, Year: ${this.year}`);
};
Object Constructor for Creating Instances:
In some scenarios, you might see developers using "Factory Functions." While similar to constructors, they don't require the new keyword and explicitly return an object.
// Factory Function (Alternative to Constructor)
function createPerson(firstName, lastName, age) {
return {
firstName: firstName,
lastName: lastName,
age: age,
greet: function() {
console.log(`Hello, ${this.firstName} ${this.lastName}!`);
}
};
}
// Creating Instances
const person1 = createPerson('John', 'Doe', 30);
const person2 = createPerson('Alice', 'Smith', 25);
// Calling Object Methods
person1.greet(); // Output: Hello, John Doe!
person2.greet(); // Output: Hello, Alice Smith!
class syntax. Under the hood, classes still use constructors and prototypes, but they provide a cleaner, more readable way to write object-oriented code.
Summary
- Object constructors are blueprints that allow you to create multiple objects with the same structure effortlessly.
- The
newkeyword is essential; it creates a new empty object, setsthisto point to it, and returns it. - Prototypes should be used for methods to save memory and improve performance in large applications.
- Using constructors helps implement Object-Oriented Programming (OOP) principles in JavaScript, leading to cleaner and more organized codebases.
- Always use PascalCase for naming your constructors to distinguish them from regular functions.