Skip to content

Instantly share code, notes, and snippets.

@0bie
Created May 15, 2016 01:29
Show Gist options
  • Save 0bie/aa52302f5e810c02f404ae73fc443c11 to your computer and use it in GitHub Desktop.
Save 0bie/aa52302f5e810c02f404ae73fc443c11 to your computer and use it in GitHub Desktop.
Module Pattern in ES5
  • It is considered best practice to manage scope using the Module Pattern
  • It enables access to both a public and private scope in your code
  • In basic terms you may get this done by wrapping a function inside a function like so:
var Module = (function() {
  var _privateMethod1 = function() {
    console.log("private 1");  
  };
  var _privateMethod2 = function() {
    console.log("private 2");
  };

  return {
      publicMethod1 : function() {
         console.log("public 1");
         _privateMethod1();
      },
      publicMethod2 :function() {
        console.log("public 2");
      }
  };
})();

Module.publicMethod1();
Module.publicMethod2();
  • In the code above we have created one public module called Module (modules should always use pascal case for easy recognition)
  • The module is an IIFE so it calls itself and is available on load
  • Inside that function we can define different methods that will be used to get stuff done
  • Private methods should always remain local & start with an _ E.g _privateMethod2
  • You never want your private methods to be in the global scope & you can do this by not returning them in the object within the Module
  • Public methods are also defined within the Module and made available to the global scope.
  • In the code above this is done by returning the public method as a key : value pair
  • To access these public methods in your code you can call them as a method on the Module E.g : Module.publicMethod2()
  • Within your code the public methods still have access to the private methods and they can be accessed like so :
  ...
  return {
    publicMethod1: function() {
       privateMethod1();
    }  
  }
  • What's going on here is that both private and public methods are local to the Module but the public methods are returned in an object by passing them as key : value pairs, thereby making them accessible methods on the Module which is in the global scope
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment