𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗖𝗼𝗻𝘀𝘁𝗿𝘂𝗰𝘁𝗼𝗿 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀
Use constructor functions to create many objects with the same structure.
A constructor function acts as a blueprint. You use the new keyword to build objects from this blueprint. You should start constructor names with a capital letter.
How it works:
When you use the new keyword, JavaScript does four things:
- It creates a new empty object.
- It sets this to point to that new object.
- It executes the function code.
- It returns the new object.
The this keyword is essential. Inside the function, this refers to your new object.
Example:
function Employee(name, salary) { this.name = name; this.salary = salary; }
const emp1 = new Employee("Ram", 50000); const emp2 = new Employee("Kumar", 60000);
Both objects share the same structure.
Adding methods:
You can add functions inside a constructor.
function Employee(name, salary) { this.name = name; this.salary = salary; this.displayInfo = function() { console.log(this.name + " earns " + this.salary); }; }
Memory management:
Adding methods directly inside the constructor creates a new copy for every object. This uses more memory.
Instead, use the prototype property.
Employee.prototype.greet = function() { console.log("Hello " + this.name); };
Now, every employee shares one single copy of the greet method. This makes your code more efficient.
Summary:
- Use object literals for single objects.
- Use constructor functions for multiple objects with the same shape.
Source: https://dev.to/dev_saravanan_journey/javascript-constructor-functions-k6k