Monday, November 8, 2021

Module pattern in javascript

Lets have an example -
var controller = (function () {
    var a = 10;  //private variable
    var add = function (a) {  //private function
        return a + 10;
    }

    return {
        publicTest: function (b) { //public method
            console.log(add(b));
        }
    }
})();

Here introducing a module pattern in javascript. 'controller'  is a module . 'a' variable and function 'add' both are inside an IIFE. we already know that an IIFE creates its own execution context .so variable 'a' and function 'add' can't be accessed outside of the the module 'controller'. This is called encapsulation .

Here , IIFE returns an empty object ,by using that object we can call 'publicTest' method.
This is the beauty of module pattern . 

Here,IIFE already return an object ,then how we access the private variable and function inside IIFE.
The answer they both accessed because of closure .

No comments:

Post a Comment

Abstract factory pattern

When single task can be done by multiple groups/family of objects and decision is taken at the runtime.