Thursday, January 19, 2017

JavaScript: Module Pattern with Anonymous Closure

Most developers create module JavaScript only with Public properties.
var ARMORY = {
  weaponList : [ * List of weapon object * ],
  removeWeapon : function(...){},
  replaceWeapon : function(...){},
  makeArmorRequest : function(...){}
};
Above module has a bunch of public variables and methods which can still be accessed by any code that know the name of the space and its properties.

What if we wanted some stuff to be accessible only to the module? Some privacy? This can be easily accomplished by wrap the entire set of properties in an anonymous immediately invoked function expression (IIFE).
var ARMORY = (function(){

  // Private
  var weaponList = [ * List of weapon object * ];
  var removeWeapon = function(...){};
  var replaceWeapon = function(...){};

  // Public
  return{
    makeArmorRequest: function(...){}
  }

})();
With IIFE, you can only have a single instance and you can call the instance without New. E.g.:
ARMORY.makeArmorRequest();

No comments:

Post a Comment