About Lesson
JavaScript Factory Functions
-
Creating Objects: Factory functions are a simple way to create multiple objects with similar properties and methods.
-
How They Work:
- A factory function is a regular JavaScript function that returns an object.
- The function takes any necessary arguments to customize the object’s properties.
-
Example:
JavaScriptfunction createPerson(firstName, lastName) { return { firstName: firstName, lastName: lastName, fullName: function() { return this.firstName + " " + this.lastName; } }; } const person1 = createPerson("John", "Doe"); const person2 = createPerson("Jane", "Smith");
-
Benefits:
- Code Reusability: Avoids repetitive code when creating multiple objects with similar structures.
- Flexibility: Easily customize object properties by passing different arguments to the function.
-
Comparison to Classes:
- Factory functions provide a simpler and more concise way to create objects compared to using classes, especially for simpler use cases.
In essence, factory functions offer a clean and efficient way to create multiple instances of objects with shared characteristics, making your code more organized and maintainable.