Discover Functional JavaScript was named one of the best new Functional Programming books by BookAuthority!
“發現功能JavaScript”被BookAuthority評為最佳新功能編程書籍之一 !
I suggest to take into consideration these ideas for building reliable objects in JavaScript:
我建議考慮以下想法以在JavaScript中構建可靠的對象:
- Split objects in two: data objects and behavior objects 將對象一分為二:數據對象和行為對象
- Make the data objects immutable 使數據對象不可變
- Expose behavior and hide data in behavior objects 公開行為并隱藏行為對象中的數據
- Build testable behavior objects 建立可測試的行為對象
數據與行為對象 (Data vs Behavior Objects)
Essentially there are two kinds of objects in an application:
本質上,應用程序中有兩種對象:
Data Objects — expose data
數據對象-公開數據
Behavior Objects — expose behavior and hide data
行為對象-公開行為并隱藏數據
數據對象 (Data Objects)
Data objects expose data. They are used to structure and transfer data inside the application.
數據對象公開數據。 它們用于在應用程序內部構造和傳輸數據。
Let’s take the case of a to-do list application.
讓我們以待辦事項清單應用程序為例。
This is how the to-do data object, gotten from the server, may look:
這是從服務器獲得的待辦事項數據對象的外觀:
{ id: 1, title: "This is a title", userId: 10, completed: false }
And this is how a data object used to display information in the view may look:
這是用來在視圖中顯示信息的數據對象的外觀:
{ id: 1, title: "This is a title", userName: "Cristi", completed: false };
As you can see, both objects contain only data. There is a small difference between them: the data object for the view has userName
instead of the userId
.
如您所見,兩個對象僅包含數據。 它們之間的差別很小:視圖的數據對象具有userName
而不是userId
。
Data objects are plain objects, usually built with object literals.
數據對象是普通對象,通常使用對象文字構建。
行為對象 (Behavior Objects)
Behavior objects expose methods and hide data.
行為對象公開方法并隱藏數據。
Behavior objects act on data objects. They may take data objects as inputs or return data objects.
行為對象作用于數據對象。 它們可以將數據對象作為輸入或返回數據對象。
I’ll take the case of the TodoStore
object. The responsibility of the object is to store and manage the list of to-dos. It makes the synchronization with the server using the dataService
object.
我將以TodoStore
對象TodoStore
。 對象的職責是存儲和管理待辦事項清單。 它使用dataService
對象與服務器進行同步。
Read Functional Architecture with React and Redux and learn how to build apps in function style.
閱讀具有React和Redux的功能架構,并學習如何以函數樣式構建應用程序。
Discover Functional JavaScript was named one of the best new Functional Programming books by BookAuthority!
發現功能JavaScript被稱為 BookAuthority最好的新功能編程書籍 !
For more on applying functional programming techniques in React take a look at Functional React.
有關在React中應用函數式編程技術的更多信息,請查看 Functional React 。
You can find me on Medium and Twitter.
您可以在Medium和Twitter上找到我。
翻譯自: https://www.freecodecamp.org/news/how-to-build-reliable-objects-with-factory-functions-in-javascript-9ec1c089ea6f/