The “Module” pattern is based on closures and consists of two components: an external function that defines a lexical environment, and the returned set of internal functions that have access to this environment.
JavaScript doesn’t have built-in support for modules, but using self-invoking functions (IIFEs) and closures you can create a modular structure.
Here is an example of the Pattern module in JavaScript:
var PatternModule = (function() { //Private variables and functions var privateVariable = 'private variable'; function privateFunction() { console.log('private function'); } //Public methods and properties return { publicVariable: 'public variable', publicFunction: function() { console.log('public function'); } }; })(); console.log(PatternModule.publicVariable); // Return 'Public variable' PatternModule.publicFunction(); // Return 'Public function'
In this example, the Pattern module is created using a self-calling function that returns an object with public methods and properties.
Inside a self-calling function, you can define private variables and functions that will not be accessible from outside the module.
This structure allows you to create modules with clear boundaries, hide the private implementation and provide only the necessary public interface to interact with the module.
Real use case
var CalculatorModule = (function() { var total = 0; function add(number) { total += number; } function subtract(number) { total -= number; } function getTotal() { return total; } return { add: add, subtract: subtract, getTotal: getTotal }; })(); CalculatorModule.add(5); CalculatorModule.subtract(2); console.log(CalculatorModule.getTotal()); // Return 3
In this example, we create a CalculatorModule that contains a private variable total and three public functions: add , subtract and getTotal. We can use these functions to add numbers, subtract numbers and get the overall result.
This modular approach allows us to hide private implementation details and provide only the necessary methods to interact with the module. This makes for cleaner and more organized code.