Structure your javascript code with module pattern

in #technology10 years ago (edited)

Module pattern is probably the most common use case of a closure. It has two characteristics: There must be an outer function that gets executed, and there must be at least one inner  function that gets returned from outer function call and keeps the  closure over the inner state (private scope). 

Revealing module pattern is the  transformation of standard module pattern, the only difference is that  the revealing module pattern was engineered as a way to ensure that all  methods and variables are kept private until they are explicitly  exposed. It makes reading code easier and allows it to be organized in a  more structured way. 

 /* Object literal pattern */
 var book = {
   title: "Gates of Fire",
   logTitle: function() {
     console.log(title)
   },
   setTitle: function(newTitle) {
     this.title = newTitle;
   }
 };

When you have typical Object literal pattern, you don't want users to  directly change object properties, in this case title of the book. The  property itself will be changed, but it's not going to be rendered  (updated) anywhere in your application. The only way we want users to  access these properties is with logTitle and setTitle methods. 

The pattern you can use instead of Object literal is Revealing module  pattern. Here we use function to wrap our methods and properties: 

 /* basic structure */
 var Module = (function() {
   /* code goes here... */
 })();

This is called immediately invoked function expression of IIFE. It  creates new scope and adds the concept of privacy. Everything inside our  module is now private and it can't be accessible outside the function,  unless otherwise specified. 

Private scope is important because we can protect our sensitive data,  but also avoid naming conflicts If you have all your functionality in  the same file or not locally scoped these naming collisions can become  nightmare. 

Here is an example of a revealing module structure: 

 var Module = (function() {

   var title = "Stardust",
       author = "Neil Gaiman",
       genre = "Fantasy";

   var getAuthor = function () {
     return author;
   };

   var setGenre = function(gnr) {
     genre = gnr;
   };

   return {
     getAuthor: getAuthor
   };

 })();

Like this, we define all our functions and variables in the private  scope and return an object with chosen parts of our module that we want  to reveal as public - our API. This way, we make it really clear at the  end of each module which parts of it are available to the outside world. 

To access our API from another module we simply prefix our exposed methods with the module name, exactly like Object literal: 

Module.getAuthor();

 

Private Naming Convention

To distinguish between private and public methods, you can follow the  private naming convention - simply add underscore (_) before the name of  the method you don't want to expose. 

 var _privateMethod = function () {
    // private
 };

 

Modules in ES6

As of ES6 we have a first class support for modules, so we will not need  to create outer wrapping functions. We can do it in much cleaner way.  It's file based, so the content of the file is treated like it exists  inside of the function and it has it's own scope. Instead of returning  things, we use export and import keyword. 

  // files.js
 var obj { data: "data" };

 export function data() {
   return obj.data;
 }

 

 import data from "files";
 data();

Thanks for reading!

Sort:  

Markdown multi line code block usage:

line 1
line 2 {
    nested line
}

You can do this by putting 4 consecutive ~ to open code block
4 consecutive ~ to close the code block.

How to verify originality:
Just mention this Steemit posting URL from your blog or twitter.

For some reason it was adding extra new lines inside multi line blocks, so I had to switch to use plain quotes.
As for the originality - I edited this post on my website so it links to this at the end. Hope I'm not gonna be questioned anymore if I'm writing my own posts.

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.082
BTC 61651.23
ETH 1639.18
USDT 1.00
SBD 0.41