JavaScript Design Patterns : Module Pattern

The module pattern is a design pattern that greatly helps to create a clean JavaScript code base. Instead of files full of random intertwined functions that call in each other in a spaghetti code fashion, the module pattern pushes us to group common functionality(functions and variables) together. By doing this we use the power of JavaScript closures to have private variables and functions that are NOT in the global scope.


In the following JavaScript code file below, we define the first part of the module which simply defines one public function, “addNumber”.

var MyApp = (function () {
    var addNumber = function(a, b){
        return a + b;
    };
    return {
        add: addNumber
    };
}());

Here in our second JavaScript file, we extend our module by adding a “multiply” function.

var MyApp = (function (myApp) {
    myApp.multiply = function (a, b) {
        return a * b;
    };    
    return myApp;
} (MyApp || {}));

In our third and last JavaScript file we add a “Circle” sub-module.  This sub-module adds a public function as well as a private variable for PI. This private variable is only accessible within the scope of Circle.

MyApp.Circle = function () {
    var pi = Math.PI;

    var calcArea = function (r) {
        return pi * r * r;
    };    

    return {
        calcArea: calcArea    
    };
}();

To show how the modules can be used we load them in a test html page:

<body>
    <a href="http://siteModule1.js">http://siteModule1.js</a>
    <a href="http://siteModule2.js">http://siteModule2.js</a>
    <a href="http://siteModule3.js">http://siteModule3.js</a>    
    console.log(MyApp.add(3, 7));
    console.log(MyApp.multiply(3, 7));
    console.log(MyApp.Circle.calcArea(2));
    console.log(MyApp.pi); //undefined, pi is not in scope    
</body>

Here are the results of the console output showing the results of our Modules working together:

javascriptmoduletest


 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s