This post aims to summarize the js patterns in Javascript Patterns book written by Stoyan-Stefanov. The category order is followed by the chapter of this book.
1 Essentials
1.1 Single var Pattern
1.2 Switch Pattern
2 Literal Patterns
2.1 Patterns for Enforcing new
If we forgot to add new, this.value will become global obejct.
2.2 Self-Invoking Constructor
2.3 Error Objects
On the other hand, throw works with any object, not necessarily an object created with one of the error constructors, so you can opt in for throwing your own objects.
3 API Patterns
3.1 Callback Pattern
3.2 Configuration Object Pattern
The configuration object pattern is a way to provide cleaner APIs, especially if you’re building a library or any other code that will be consumed by other programs.
4 Performance Patterns
4.1 Self-Defining Functions
This pattern is useful when your function has some initial preparatory work to do and it needs to do it only once.
A drawback of the pattern is that any properties you’ve previously added to the original function will be lost when it redefines itself.
4.2 Memoization Pattern(Function Properties)
You can add custom properties to your functions at any time. One use case for custom properties is to cache the results (the return value) of a function, so the next time the function is called, it doesn’t have to redo potentially heavy computations. Caching the results of a function is also known as memoization.