Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Implementing Modular Design pattern and OOP in JavaScript

4.00/5 (3 votes)
4 Jan 2016CPOL3 min read 12.7K  
How to implement Modular Design pattern and OOP in JavaScript

Introduction

JavaScript and HTML are well known languages for web application development, and as a web developer it’s been a long time I have been working with these two languages.

As a web application architect and developer, we have to take care of both Server and client side programming languages. I have worked with lot of web applications/websites where I was involved in design and development. You may be aware that there are a lot of OOPS practices and principles which you have been implementing in your application in order to deliver successful projects.

There are SOLID principles and well known design patterns. I have seen and implemented few of them in my practice on Server Side programming (mostly C#), but I found a lack of these principle and patterns in client side programming language like JavaScript.

However, it’s been a while when we got good frameworks for client side development, and it’s worth mentioning JQuery, Backbone, Amber and AngularJS which are open source come up with a web established framework to deliver rich client application.

In most of the cases, I have seen when time comes to write some client side code using JavsScript or Jquery, most of us use to write all the JavaScript function and variables in the same HTML/cshtml/aspx/jsp/php document where those are required. For example:

Here is a function to perform client side validation for age:

JavaScript
function validateAge()
{
    var age = parseInt ($('#age').val());
    if(age<20){
        $('#error').html('Please enter a valid age');
    }
}

And generally, we attach this in submit button or input element and perform age validation on change.

And when our application moves towards complexity, we pollute global or window scope using this approach.

In this tip, I am going to explain how to can create namespaces or modules, and further we will implement generic method in those modules.

Since JavsScript doesn’t have any concept like class which we are familiar in many OOPS languages, but it can be achieved using constructor function.

Let’s have a look into the above function which is being used to verify age:

Problem: We cannot re-use this function in other views/pages. So wherever we will require age validation, we need to copy and paste L.

Solution: Create a separate module.

Create a module for your application.

JavaScript
var validationModule = {
        config: {
            ApplicationName: 'Default',
            validationEnabled:true
        },
        validateAge: function (element) {
            if (this.config.validationEnabled == true) {
                return (parseInt($(element).val()) > 20);
            }
            else { throw 'Validations are disabled'; }
        }
    };

Now, you are free to use this anywhere in your application in any way you want to use.

If you want to use this inside script, you can use it like:

JavaScript
var myApp= validationModule;
var isValidAge = myApp. validateAge($('#age'));

Problem: Whenever we declare any variable in JavaScript, there might be two cases:

  1. Global variable
    var VERSION=1.2.0;
  2. Private variable:
    JavaScript
    function getDateOfBirth()
    {
        // private variable
        var age = parseInt($('#age').val()) ;
        var dob=( new Date().getFullYear())-age;
        return dob;
    }
    

There is a misconception about the scope of variable:

JavaScript
var config={user:'Anupam'}

function VerifyUser() {

    if (config.user == 'Anupam')
    {
        var text = 'hi ' + config.user;
    }
    else {

        // invalid user

    }
    // text has scope beyond if block
    console.log(text);
}
VerifyUser();
console.log(text); // now undefined

Tip: If we define any variable without using var keyword anywhere in JavaScript, its gets injected in global scope. Example: x=’test’;

Try to run this example in your document and see the output. Since we defined variable text inside if block but this is still available afterword the block.

While implementing modular programming in our application, we can work with private member efficiently with the help of constructor function (if you are an AngularJS developer you might be aware of service, which is a very good example of constructor function).

Module with Constructor Function and with Private Members

Here is the same example with constructor function, using which we can use private members:

JavaScript
var validationModule = (function () {

    // current scope to variable module
    var module = this;

    // private variable
    var defaultConfig = {
        ApplicationName: 'Default',
        validationEnabled: true
    };

    module.getConfig = defaultConfig;

    module.setConfig = function (config) {
        defaultConfig.ApplicationName = config.ApplicationName;
        defaultConfig.validationEnabled = config.validationEnabled;
    };

    module.validateAge = function (age) {
        if (defaultConfig.validationEnabled == true) {
            return (parseInt(age) > 20);
        }
        else { throw 'Validations are disabled'; }
    }
    // return module
    return module;
})();

Now using this module all the members which are module.* will be available in your application, because it is return type of our module. And you can also work with private member.

We can also share properties or global object using constructor parameter as follows:

JavaScript
(function (window,$) {
// work with global window and JQuery object here
})(window,JQuery);

It was a quick start to develop large application using modular approach, so that we can handle dependencies easily in large applications. You can add events and can also extend your module using JavaScript prototype.

Hope you have enjoyed and learned how we can OOP flavor in JavaScript. It would be my pleasure to answer and entertain your queries/suggestion.

Please note: This post is also shared in c-sharpcorner.com.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)