Apr 22, 2015
**Disclaimer: This is on ES5 not ES6
The above is just an example of an object being used to store data, but since functions are also objects that can be passed around, it is totally possible to start making interfaces, classes, and more with these.
So let’s talk a bit about what a design pattern is. Design patterns are blocks of code that developers use over and over again to solver similar problems. Specifically, we are going to look at the Revealing Module Pattern, and the Singleton Pattern.
The Revealing Module Pattern
The Singleton Pattern
The singleton pattern is used when you want the stand alone nature of a static class, but also have the ability to pass an object around. Typically, you only want only one instance of this class to exist. This could be used for making a database connection to avoid multiple connections that will affect performance, or possibly a shopping cart for an ecommerce website.
This works by having an automatically executing function set cart to a function that does the following.
- Check to see if a variable self exists and return that variable.
- If self has not been found, the program will continue and set self to the current object. This should only happen the first time the singleton object is created.
- Appends new properties and methods to itself.