Basic Factory Function Pattern
You'll learn how to create a simple factory function that builds and returns custom objects.
What Is a Factory Function?
A factory function is simply a function that returns a new object every time you call it. Think of it like a factory assembly line: you call the function, it assembles an object with the properties and methods you need, and hands it back to you—ready to use.
Unlike object literals (which you write once), a factory lets you create many similar objects without repeating code.
Writing Your First Factory
Here's a basic pattern:
function createUser(name, age) {
return {
name: name,
age: age,
greet: function() {
console.log(`Hi, I'm ${this.name}!`);
}
};
}
const user1 = createUser('Alice', 28);
const user2 = createUser('Bob', 35);
user1.greet(); // "Hi, I'm Alice!"
user2.greet(); // "Hi, I'm Bob!"
The factory function createUser accepts parameters and returns a brand-new object each time. Every object has its own name, age, and greet method.
Why Use This Pattern?
- Reusability: Create multiple similar objects without copying code
- Encapsulation: All object creation logic lives in one place
- Flexibility: You control exactly what each object contains
Key Takeaway: A factory function is just a function that returns an object—it's a clean, reusable way to create multiple objects with the same structure.