JavaScript: Module Patterns

The Structure of the Module Pattern

by sjmcpherson

JavaScript

// Module Pattern creats a structure for Private & Public Methods to be created. Public Methods are exposed in the return statement
var MY_APP_ONE = (function() {
  // Private variables
  var secret_1 = 'Hello';
  var secret_2 = 'World';

  // Publicly exposed
  return {
    foo: function() {
    },
    bar: function() {
    }
  }
})();

// "Revealing" Module Pattern
var MY_APP_TWO = (function() {
  // Private variables
  var secret_1 = 'Hello';
  var secret_2 = 'World';

  function foo() {
  }
  function bar() {
  }

  // "Revealed" here, otherwise private
  return {
    foo: foo,
    bar: bar
  }
})();