𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗖𝗼𝗻𝘀𝘁𝗿𝘂𝗰𝘁𝗼𝗿 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀
A constructor function is a blueprint for objects. Use it to create many objects with the same structure.
How it works:
You use the new keyword to call a constructor function. This process does four things:
- It creates a blank object.
- It sets this to point to that new object.
- It executes the code inside the function.
- It returns the new object.
Example code:
function Employee(name, salary) { this.name = name; this.salary = salary; }
const emp1 = new Employee("Saravanan", 50000);
Rules to follow:
- Start function names with a capital letter.
- Use this to assign properties to the new object.
The role of this:
Inside a constructor, this refers to the specific object you are making. For example, this.name = name assigns the parameter value to the object property.
Adding methods:
You can add functions inside a constructor so every object can use them.
function Employee(name, salary) { this.name = name; this.salary = salary; this.displayInfo = function() { console.log(this.name + " earns " + this.salary); }; }
Memory efficiency:
If you add methods directly to the constructor, every object gets its own copy. This uses more memory.
Instead, use the prototype. Adding a method to the prototype shares one single copy among all objects.
Employee.prototype.greet = function() { console.log("Hello " + this.name); };
Summary:
- Use object literals for a single object.
- Use constructor functions for multiple objects with the same shape.
Source: https://www.w3schools.com/js/js_object_constructors.asp Source: https://www.geeksforgeeks.org/javascript/javascript-function-constructor/ Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
Post link: https://dev.to/dev_saravanan_journey/javascript-constructor-functions-k6k