Revealing module pattern in Javascript
Design patterns are crucial for writing maintainable, readable and reusable code. There is a diverse list of design patterns we can use with Javascript. In this article I will provide an intro to the the revealing module pattern, which is useful in many cases.
Although ES6 modules have replaced this technique and have been implemented in today’s major browsers, it is still useful if you are not using a transpiler.
A design pattern is a term used in software engineering for a general, reusable solution to a commonly occurring problem in software design.
First we wrap out function inside an IIFE (immediately invoked function expression) to create a local scope for our functions and variables.
const myWidget = (function() { ... })();
With this function we can return an object referring to methods that we want to expose publicly. These public methods are the only ones who have access to our private methods and variables inside our myWidget function.
In this example, we are getting the likes of Jenny and also adding a like called ‘travel’. Outside our module, we are only allowed to call the myWidget.getLikes() method, we do not have access to the data object or the addLike method which are private.
Advantages
It allows us to write more consistent code and also makes clear which variables and functions are accessed publicly.
Disadvantages
When you have a private function that refers to a public function, you can not override that public function when you want to change or update your module. This is why modules created with the Revealing Module pattern may be more fragile than modules from the original module pattern.
ES6+
With the introduction of the let **and **const keywords we are able to create block scoped pieces of code to make sure our variables are private. Before this was only possible inside a function or IIFE (immediately invoked function expression). Also we can use the import and export declarations to divide our code up into modules and declare local variables. Make sure to use a transpiler because to support all browser, e.g. Babel. Or use a bundler that already has a compiler included, e.g. webpack or pacel.
Top comments (0)