𝗙𝗮𝗰𝘁𝗼𝗿𝘆 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗮𝗻𝗱 𝗖𝗼𝗻𝘀𝘁𝗿𝘂𝗰𝘁𝗼𝗿 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁
Creating objects one by one is a mistake.
If you write a manual object for every user or classmate, you repeat code. If you have 100 users, you write the same logic 100 times. This leads to bugs. You might accidentally change a property later and break your application.
Use these two patterns instead to write clean code.
- Factory Functions
Think of a real factory. Raw materials go in. A finished product comes out.
A factory function takes parameters and returns a new object.
Example:
function classFactory(name) {
return {
reply() {
return ${name} is present
}
}
}
The benefits:
- You write logic once.
- You reuse the function for every new object.
- Data stays safe. The name stays inside the function scope. You cannot accidentally overwrite it from the outside.
- Constructor Functions
Constructor functions also create objects. They use the "new" keyword and the "this" keyword. By convention, you start these with a capital letter.
Example:
function Classmate(name) {
this.name = name
this.reply = function() {
return ${this.name} is present
}
}
When you use "new", JavaScript does the work for you:
- It creates a new object.
- It assigns it to "this".
- It returns the object automatically.
You do not need a "return" statement.
Scaling your code
You can combine these patterns with arrays to handle large amounts of data. Instead of typing every name, use a map function.
Example: const names = ['Kali', 'Andrew', 'Pearl', 'Percy'] const classmates = names.map(name => new Classmate(name))
Now you have a list of objects ready to use.
Summary:
- Avoid manual object creation to prevent repetition.
- Use Factory Functions to encapsulate logic and protect data.
- Use Constructor Functions to leverage the "new" keyword for automatic object creation.
- Always write your logic once and reuse it everywhere.
Source: https://dev.to/pearlodi/factory-functions-and-constructor-functions-in-javascript-lmb