𝗖𝗼𝗻𝘀𝘁𝗿𝘂𝗰𝘁𝗼𝗿𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁
Creating objects one by one is slow. If you need ten students with the same properties, you waste time writing the same code repeatedly.
JavaScript solves this with Constructor Functions.
Think of a constructor as a blueprint. A blueprint for a house is not a house, but you use it to build many houses.
How it works:
A constructor is a special function. You use the new keyword to create objects from it.
Example:
function Student(name, age, city) { this.name = name; this.age = age; this.city = city; }
const student1 = new Student("John", 21, "Chennai"); const student2 = new Student("David", 22, "Madurai");
Why use this?
- It saves time.
- It prevents code repetition.
- It creates a standard structure for your data.
The Role of this:
Inside a constructor, the word this refers to the new object you are making.
If a teacher says "my classroom," the word "my" points to that specific teacher. In code, this.name points to the name of the specific object you just created.
What happens when you use new?
When you run const emp = new Employee("John", 50000), four steps occur:
- JavaScript creates an empty object.
- The this keyword points to that new object.
- The properties are added to the object.
- The object is returned to you.
Adding Actions:
Objects can do more than hold data. They can perform actions. In programming, these actions are called methods.
Example:
function Laptop(brand, ram) { this.brand = brand; this.ram = ram; this.showDetails = function() { console.log(this.brand, this.ram); }; }
The Laptop object now holds data and a function to show that data.
Best Practices:
- Always capitalize the first letter of a constructor. Use Student, not student. This tells other developers to use the new keyword.
- Always use the new keyword. If you forget it, the function acts like a normal function and breaks your code.
Comparison:
Object Literals:
- Good for one single object.
- Simple and fast.
- No blueprint.
Constructor Functions:
- Good for many objects.
- Reusable and organized.
- Uses a blueprint approach.
Source: https://www.w3schools.com/js/js_object_constructors.asp Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor Full post: https://dev.to/annapoo/constructor-in-javascript-4nbm