Home Web Front-end JS Tutorial Quick Tip: What Are Factory Functions in JavaScript

Quick Tip: What Are Factory Functions in JavaScript

Feb 17, 2025 am 10:54 AM

Quick Tip: What Are Factory Functions in JavaScript

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

  • Factory function: Returns the function of the object.
  • Parameterized factory function: Accept parameters to change the factory function that returns the object structure.
  • Composite factory functions: Build factory functions of complex objects by combining other factory functions.
  • Asynchronous factory function: Returns the factory function of the Promise to handle asynchronous operations.
  • Advanced factory functions: Factory functions passed as function parameters, used to create enhancers (e.g., add timestamps or create immutable objects).

Simple Example

A simple factory function:

function createJelly() {
  return {
    type: 'jelly',
    colour: 'red',
    scoops: 3
  };
}
Copy after login
Copy after login

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
  };
}
Copy after login

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()
    ]
  };
}
Copy after login

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 {}
Copy after login

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()
  };
}
Copy after login

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);
  });
}
Copy after login

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
  };
}
Copy after login

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`),
    // ...
  ]);
}
Copy after login

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
  };
}
Copy after login
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles