Monday, July 11, 2016

JavaScript Module Pattern & Closures

If you want to write well-organized JavaScript code, Or want to understand the concept behind almost all famous client side frameworks like jQuery, Angular, etc. … 
So you should know the following basics:

First Back To basics to be sure we will understand.

Object Literal syntax:

        var myObj = {
            defaults: { name: 'nady', age: 33 },
            myMethod: function () {
                // Do something
            }
        };

       myObj.myMethod();


Normal Function :
       function myClosureFunction() {
            alert('Called');
        }

       myClosureFunction();

Anonymous function 
       var anon = function () {
            alert('anonymous Func');
        };
        anon();

Or Simply using Closure:
-          You can declare a function that call itself immediately (Self-Executing).

       (function () {
            alert('Called');
        })();

-          The last parentheses , for calling itself so we can pass parameter like :

(function (message) {
            alert(message);
 }('called'));


Module Concept:
Simply the Module encapsulate your code like a class in other programming languages .

Creating Namespace to access our anonymous function (Module)
Declaring module in global scope enable us to call it everywhere, also we can call it from other modules.
        var myModule = (function () {
            //Code
        })();


Private Methods & Variables:
-          JavaScript variables can belong to the local or global scope.
-          Private variables can be achieved using closures.
-          Closure creates its own scope out of global scope.

       var myModule = (function () {
            var privateVar = 22;
            var privateMetod = function () {
                alert('Called');
            }
        })();


Public & Return
 Returning an Object with a function as a property:
       var myModule = (function () {

            return {
                publicMethod: function () {
                    alert('hi');
                }
            };

        })();

        myModule.publicMethod();


Define all our “private” stuff locally and only return, “the public objects”.

var myModule = (function () {

            var privateMethod = function () {
                alert('privateMethod Called');
            };

            return {
                publicMethodOne: function () {
                    alert('publicMethodOne Called');
                },
                publicMethodTwo: function () {

                },
                publicMethodThree: function () {

                }
            };

        })();

        myModule.publicMethodOne();
       // myModule.privateMethod()  you can't call this

//--------------------------------
       var myModule = (function () {

            // locally scoped Object
            var myObject = {};

            var privateMethod = function () { };

            myObject.someMethod = function () {
                alert('Hi');
            };

            return myObject;

        })();

        myModule.someMethod();

//------------------------------------
var myModule = (function () {

            var privateMethod = function () {
                // private
            };

            var methodOne = function () {
                // public
            };

            var methodTow = function () {
                // public
            };

            return {
                methodOne: methodOne,
                methodTow: methodTow
            };

        })();
//---------------------------------------------

Extend our Module

    var myOriginalModule = (function () {

            var privateMethod = function () {
               // Code
            };


        })();

        var myExtendedModule = (function (myOriginalModule) {

            myOriginalModule.myNewMethod = function () {
                // another method!
            };

            return myOriginalModule;

        })(myOriginalModule || {});


-> Notice (Module || {}) this is incase Module is undefined -it instantiate a new Object, and bind our extension method to it, and return it, to avoid errors.



1 comment:

Mostafa Eldeeb said...

its really benefit for all web developers and nice topic