JavaScript factory functions: build powerful patterns for composing objects
JavaScript factory function is a function that returns an object, and can create multiple similar objects without using the new
or this
keywords. This article will explore several uses of factory functions, including parametric factory functions, composable factory functions, asynchronous factory functions, and advanced factory functions, showing how to use them to build more flexible and easier to maintain JavaScript code.
Core Concepts
Simple Example
A simple factory function:
function createJelly() { return { type: 'jelly', colour: 'red', scoops: 3 }; }
Every time the createJelly()
function is called, a new jelly object instance will be returned. Function names do not necessarily start with create
, but doing so can improve the readability of the code.
Parameterization factory function
Like all functions, factory functions can also accept parameters to change the structure of the returned object:
function createIceCream(flavour = 'Vanilla') { return { type: 'icecream', scoops: 3, flavour }; }
While theoretically a large number of parameters can be used to create very specific nested objects, this does not fit the idea of combinations.
Composite factory function
By defining one factory function as a combination of another, complex factory functions can be broken down into smaller, more reusable fragments. For example, we could create a dessert factory function based on the previous jelly and ice cream factory function:
function createDessert() { return { type: 'dessert', bowl: [ createJelly(), createIceCream() ] }; }
By combining factory functions, you can build any complex structure without using new
or this
.
Combination vs. Inheritance
Combinations tend to be more inclined to the “has-a” relationship, while inheritance tends to be more inclined to the “is-a” relationship. For example, implement Trifle with inheritance:
// Trifle is a Dessert function Trifle() { Dessert.apply(this, arguments); } Trifle.prototype = Dessert.prototype; // 或使用 ES6 class class Trifle extends Dessert {}
and use combination to implement Trifle:
// Trifle has layers of jelly, custard and cream. It also has a topping. function createTrifle() { return { type: 'trifle', layers: [ createJelly(), createCustard(), createCream() ], topping: createAlmonds() }; }
Async factory function
Not all factory functions can return data immediately. Some factory functions may need to get the data first. In these cases, the factory function that returns a Promise can be used:
function getMeal(menuUrl) { return new Promise((resolve, reject) => { fetch(menuUrl) .then(result => { resolve({ type: 'meal', courses: result.json() }); }) .catch(reject); }); }
To avoid too deep nesting, the asynchronous factory function can be decomposed into multiple independent factory functions and then combined:
function getMeal(menuUrl) { return fetch(menuUrl) .then(result => result.json()) .then(json => createMeal(json)); } function createMeal(courses = []) { return { type: 'meal', courses }; }
You can use Promise.all
to combine multiple factory functions that return a promise:
function getWeeksMeals() { const menuUrl = 'jsfood.com/'; return Promise.all([ getMeal(`${menuUrl}/monday`), // ... ]); }
Functions and methods
Factory functions usually do not return objects containing methods, because this mixes the data and the calculations together. Factory functions focus on creating data objects, while the logic of manipulating data is processed by independent functions.
Advanced Factory Function
Passing factory functions as higher-order functions can achieve powerful control. For example, you can create an enhancer using advanced factory functions:
function createJelly() { return { type: 'jelly', colour: 'red', scoops: 3 }; }
This enhancer takes an existing factory function and wraps it into a factory function that returns an instance containing a timestamp.
Conclusion
Factory functions are a simple and powerful pattern that encourages the use of composition rather than inheritance, creating more flexible, easier to test and maintain code. By using simple building blocks, the code can be made easier to understand and maintain.
(The following is the FAQ part, which has been rewritten according to the original text, and similar issues have been streamlined and merged)
FAQ (FAQ)
The difference between factory functions and constructors? The factory function returns the object directly without the new
keyword; the constructor uses the new
keyword and uses this
to point to the newly created object. Factory functions are more flexible and more in line with functional programming style.
How to create private variables in factory functions? Use closures. Private variables are declared inside the factory function and can only be accessed through methods in the object returned by the factory function.
Can factory functions be used with ES6 arrow functions? Yes.
How to add methods to factory functions? Define method in the object returned by the factory function.
Can factory functions inherit other factory functions? You can combine multiple object properties with Object.assign
or expand operators to simulate inheritance.
What role does closures in factory functions? Closures implement data encapsulation and create private variables and methods.
Can factory function return other functions? Yes, this is often used to create higher-order functions.
How to use factory functions with JavaScript modules? Export the factory function, then import and use it in other modules.
The above is the detailed content of Quick Tip: What Are Factory Functions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!