Thursday, November 28, 2019

JavaScript: Define Multiple Instance in Module Pattern

In JavaScript: Module Pattern with Anonymous Closure article, I have shown you how to create a Module using Immediately-Invoked-Function-Expression (IIFE). With IIFE, you only can have a single instance of the object.

What if you need to have multiple instances? Example two armies carry different weapons.

Remove () in the ARMORY module in the previous Article.
var ARMORY = (function(){
  // Private
  var weaponList = [ * List of weapon object * ];
  var removeWeapon = function(...){};
  var replaceWeapon = function(...){};

  // Public
  return{
    makeArmorRequest: function(...){}
  }
});
Now you can create multiple instances:
var army1 = new ARMORY();
var army2 = new ARMORY();