DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. JavaScript
  4. Patterns in Large Scale JavaScript Applications, Part 2

Patterns in Large Scale JavaScript Applications, Part 2

In today's post, we take a look at the modular design pattern common to large-scale JavaScript web applications, and some common ways it's used.

Puneet Sharma user avatar by
Puneet Sharma
·
Dec. 15, 17 · Tutorial
Like (5)
Save
Tweet
Share
11.17K Views

Join the DZone community and get the full member experience.

Join For Free

It is clear from Part 1 of this series what a pattern is in the software development process, why we use software design patterns, and the factors for using design patterns in JavaScript. If you haven’t read the previous post, i would recommend you to please read it once to get the overview.

I am a very big fan of JavaScript’s module design pattern. That’s the object literal pattern in the category of modular design patterns.

What Is a Module Pattern?

The module pattern is one of the design patterns, not only in Javascript, that encapsulates PRIVACY and STATE using Closures.

Image title

It gives us a way to encapsulate the private and public methods and variables and to protect our methods from the global scope.

Code Snippet:

Below is the example of a Shopping Cart that’s being implemented with the module pattern. The Shopping Cart 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 only the methods (addProduct, getProductCount, getTotalProducts) that are within the 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;
        }

    }

}());

InsideshoppingCartModule, we have returned an object that gets automatically assigned to shoppingCartModule.

So you can access these methods as 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 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 organize code by the behaviors in your current application’s features. So, here, we are preventing our application from accessing the global variables, which is common a practice for software development, and especially, for large-scale JavaScript applications.

Image title

In modular JavaScript, you can use one module more than one time in your application, like the project in which I want to get the customer’s query to register on each page. So the functionality is going to be same for each page that's taking the data from the query form when the Submit button is clicked, and then an email will be sent to my 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 is declaring a function that’s calling itself immediately. If you want, you can read more about it here.

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

JavaScript doesn’t have privacy, so we need to return only the parts we need and leave the other code out of the global scope.

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

Private Feature Methods:

Again, since “JavaScript doesn’t have privacy,” it doesn’t have private methods either. But we can create a working equivalent.

Image title

You all know what a private method is, it's a method that can’t be called/seen outside of its scope. So we can use the closure to protect 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 its scope, JavaScript will throw an error.

Return in Modules:

Mostly complex modules use the return function 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 below code, 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;


})();

I hope now you have a clear understanding of the modular design pattern. In the next post, we will look at how to consolidate jQuery Ajax calls and consume them with our modular design pattern.

JavaScript application

Published at DZone with permission of Puneet Sharma, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How To Best Use Java Records as DTOs in Spring Boot 3
  • Microservices Testing
  • What Are the Different Types of API Testing?
  • A Gentle Introduction to Kubernetes

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: