SoFunction
Updated on 2025-04-10

JavaScript design pattern module (module) pattern

Modules are an integral part of any powerful application and often help us clearly separate and organize code units in projects.

Methods to implement modules in js:
1. Object literal representation
model
Module
Module
Harmony module

Object literal

Object literals do not need to be instantiated using the new operator, but cannot be used at the beginning of a statement, because the beginning may be interpreted as the beginning of a block. Outside the object, new members can be added to the object literal using the following assignment statement, = "someValue".

var myModule = {
 myProperty:"someValue",
 myConfig:{
 useCaching:true,
 language:"en"
 },
 //Basic Method myMethod:function(){
 //...
 },
 //Output information according to the current configuration myMethod2:function(){
  ("Caching is:"+() ? "enabled":"disabled");
 },

 //Rewrite the current configuration myMethod3:function(newConfig) {
 if(typeof newConfig ==="object"){
   = newConfig;
  ();
  }
 },


};
myModule.myMethod3({
language:"fr",
usecaching:false
})

Using object literals helps encapsulate and organize code.

In javascript, the Module pattern is used to further simulate the concept of classes, in which way a separate object can have public/private methods and variables, thereby blocking special parts from the global scope.

The module pattern uses closures to encapsulate "private" state and organization. It provides a way to wrap a mix of public/private methods and variables to prevent leaks to the global scope and conflicts with other developers' interfaces. Through this mode, you only need to return a public API, and everything else is maintained in a private closure.
In module mode, due to the existence of closures, declared variables and methods are only available within the mode, but variables and methods defined on the return object are available to external users.

Implementation of module mode

var testModule = (function(){
 var counter = 0;
 return {
  incrementCounter:function(){
   return ++counter;
  },
  resetCounter:function(){
   ("counter value prior to reset" + counter);
   counter = 0;
  }
 }
})();

//Increase the counter();

//Check the counter value and reset();

The other part of the code is that incrementCounter() and resetCounter() cannot be read directly. The counter variable is actually completely isolated from the global scope, so it acts like a private variable whose existence is limited to the closure of the module, because the only code that can access its scope is these two functions. The above method has effectively set the namespace, so in the test code, all calls need to be prefixed.

//Module mode containing namespace, public, and private variablesvar myNamspace = (function(){
 //Private counter variable var myPrivateVar = 0;

 //Record private functions with parameters var myPrivateMethod = function(foo){
  (foo);
 };

 return {
  //Public variables  muPublicVar:"foo",

  //Call public functions that call private variables and methods  myPublicFunction:function(bar){
   myPrivateVar++;
   myPrivateMethod(bar);

  }
 }
})();

Reference global variables
JavaScript has a feature called implicit global variables. Regardless of whether a variable has been used or not, the JavaScript interpreter reverses the scope chain to find the var declaration of the entire variable. If the var is not found, the interpreter assumes that the variable is a global variable. If the variable is used for assignment operation, if it does not exist before, the interpreter will automatically create it. This means that it is very easy to use or create global variables in anonymous closures, but the more difficult thing is that the code is difficult to manage, especially when people who read the code see many differentiate between which variables are global and which are local.

Fortunately, in anonymous functions, we can provide a relatively simple alternative. We can pass global variables into anonymous functions as a parameter and use them. Compared with implicit global variables, it is clear and fast. Let's take an example:

//Global modulevar myModule = (function(jQ,_){

  function privateMethod1(){
    jQ(".container").html(test);
  }
  return {
    publicMethod:function(){
      privateMethod1();
    }
  }
})(jQuery,_);
();

//Global modulevar myModule = (function(){
//Module objectvar module = {};
privateVariale = "Hello";

function privateMethod(){
  //...
}
 = "Foobar";
 = function(){
}  
return module;

 })(); 

Declare global variables without implementing them and can also support the concept of global introduction

There are still certain shortcomings in the Module mode:
1. Since we access public and private members differently, when we want to change visibility, we actually have to modify each existence that has ever used that member.
2. We cannot access those private members added to the method later.
3. Unable to create automated unit tests for private members, and additional complexity is added when bugs need to be fixed.
4. Developers cannot easily extend private methods

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.