A module is not a native JavaScript construct. It is a coding pattern to minimize the corruption of the global scope.
1. Global Scope and Functions
When a function is declared, it is located in the global scope unless it is declared inside of another function. When the size of a site grows, you might include many JavaScript files into a single page. When all functions are global, there are chances of name conflicts.
2. Self-Executing Anonymous Functions as Modules
The simplest module is a self-executing anonymous function.
function doSomething() { console.log("..."); } doSomething();
The code creates the “doSomething()” function in the global scope.
(function () { console.log("..."); })();
3. Why Modules
The previous example is not helpful much, isn’t it?
Let’s move on to the general module. You need to use a self-executing anonymous function in a more clever way. A module is a function that encapsulates a number of functions and expose only required ones as global functions.
function add(a, b) { return a + b; } function multiply10(a) { return a * 10; } function calculate(a, b) { return multiply10(add(a, b)); } console.log(calculate(3,4)); // 70
The client will only call the “calculate()” function. Other functions are helper functions. But JavaScript runtime creates all functions in the global scope.
4. Modules
If functions are declared inside another function, they are in the local scope. Put all functions inside a self-executing anonymous function.
(function () { function add(a, b) { ... } function multiply10(a) { ... } function calculate(a, b) { ... } })();
Now we have another problem. All function are local and cannot be accessed from outside.
The solution is to use the global object. Create a global object and expose a function as a method of an object.
var myObj = {}; (function () { function add(a, b) { ... } function multiply10(a) { ... } myObj.calculate = function (a, b) { ... } })(); console.log(myObj.calculate(3, 4)); // 70
This approach works but it is not elegant. The better way is to use the pre-existing global object such as “window“.
(function (myObj) { function add(a, b) { return a + b; } function multiply10(a) { return a * 10; } myObj.calculate = function (a, b) { return multiply10(add(a, b)); } // checks the "window.myObject" is defined in the global // if not, create an empty object })(window.myObject = window.myObject || {}); console.log(window.myObject.calculate(3, 4)); // 70