Full Stack Solutions
Javascript Design Pattern (1)

Pattern in Large Scale JavaScript Applications (Part -2 of 8)

It is clear from the Part – 1 of the Post that what is a Pattern  in the Software Development Process and why we use the Software Design Pattern and the factors behind using Design pattern in JavaScript.If you haven’t read the previous post, i will recommend you to please read it once to get the overview.

I am very big fan of JavaScript’s Module Design Pattern.That’s the Object Literal Pattern in the category of Modular Design pattern.

What is Module Pattern ?

The Module Pattern is one of the Design Pattern that encapsulates PRIVACY & STATE using Closures in JavaScript.


scalable-javascript-design-patterns-27-728
It gives us the way to encapsulate the private and public methods and variables and protect our methods from the Global Scope.

Code Snippet :

Below is the example of Shopping Cart Module that’s being implemented with the Module Pattern.shoppingCart Module is itself a Global module. Cart is an Array that’s Private so that other parts of the module can’t access it directly.

So the only methods (addProduct(),getProductCount(),getTotalProducts()) that are within the scope of module’s closure will be able to access it.

var shoppingCartModule = (function() {

    var cart = []; //private array
   
    return { 

        //exposed to public methods and variables

        addProduct: function(item) {
            cart.push(item);
        },

        getProductCount: function() {
            return cart.length;
        },

        getTotalProducts: function(){
           var total = this.getItemCount();
           p=0;
            while(total--){
                p+= cart[total].price; 
            }
            return p;
        }

    }

}());

Inside the shoppingCartModule we have return an Object that automatically assigned to shoppingCartModule.
So you can access these methods by follows :

shoppingCartModule.addProduct({item:'JS Guide',price:$50});
shoppingCartModule.addProduct({item:'Design Pattern',price:$33});


console.log(shoppingCartModule.getProductCount());
console.log(shoppingCartModule.getTotalProducts());

So if you will try to access the (shopingCartModule.basket) this will not work, because it will only work within the scope of the Closure.

 

Object Literal Pattern

The Object Literal Pattern is used to organise the code by the behaviors in your current Application’s Feature.So here we are preventing our Application from the Global Variables,which is a good practice for Software Development Process and specially for the Large Scale JavaScript Applications.


scalable-javascript-design-patterns-36-728
 

In Modular JavaScript you can use one module more than one time in your whole Application,like i have done in my Project.I want to get the Customer’s Query in each page.So the functionality is going to be same for each page that is to taking the data of Query form on Submit click and then mail to Email ID.

An Object Literal is a way to encapsulate related features, as shown here:

var myObjectLiteral = {
    myFearure1 : function() {
        /* do something */
    },

    myFeature2 : function() {
        /* do something else */
    }
};

  > Module Creation

The following Code snippet that is declaring a function that’s calling itself immediately.If you want to read more about it here.

    (function () {
          // code
    })();

JavaScript doesn’t have privacy. So we need to return only that parts that we need and leaving the other code out from the Global Scope.

We have declared a myObjectLiteral Module in the global scope so that we can call it whenever we want and wherever we want and we can also pass one module to the another modules.

  > Private Feature Methods :

Repeating the same call “JavaScript doesn’t have privacy” ,so it don’t have private methods too but we can create a working equivalent.


scalable-javascript-design-patterns-37-728
You all know what a Private method is,a method that can’t be call/see outside of the scope.So we can use the closure at protecting our code.

 var myObjectLiteral = (function () {
  
          var privateMethod = function () {
            // your feautre code
          };

})();

In the above example myObjectLiteral is locally declared inside the scope.So if we call that function outside of it’s scope
JavaScript will throw an error.

  > return in Modules :

Mostly Complex Modules use the return by returning an object to the Module.All methods are bound to that Object that can be accessible.

var myObjectLiteral = (function () {
  
    var localObject = {};

    var privateMethod = function () {};

    localObject.privateMethod = function() {

        // private method define

    };

    return localObject;


})();

  > Local Objects :

Local Objects are those which are declared inside the scope.In the last localObject is returned so we only get the actual/original Object sent back.

var myObjectLiteral = (function () {
  
    var localObject = {};

    var privateMethod = function () {};

    localObject.privateMethod = function() {

        // private method define

    };

    return localObject;


})();

Till now you have Clear understanding of Modular Design Pattern.In the next Post We will understand Consolidate Jquery AJAX Calls and consuming this with our Modular Design Pattern.

  • paulwilkins

    Some corrections:
    “It Modular JavaScript” -> “In Modular JavaScript”
    “myFearure1” -> “myFeature1”
    “Following Code snippet that is declaring a function” -> “The following Code snippet that is declaring a function”
    “call it whenever want” -> “call it whenever we want”
    “privacy, So” => “privacy. So”
    “decalred” => “declared”
    Some (all?) commas and fullstops also have bad spacing around them.

    I recommend that you read over what you wrote after you’ve written it, and have someone else read through it before you publish your next post.

    • puneet sharma

      Hi paulwilkins thanks for reading this article and for your corrections.
      I was busy in researching with some assignment so in hurry i just publish them.
      I am implementing your suggestions and i appreciate your efforts 🙂

  • blaster151

    I encourage you to get some editing help with these posts as they are rife with misspellings and grammatical errors.

  • gridlove_ad_300x250.jpg