12 October 2014

Revealing Module Pattern in Javascript

Revealing Module Pattern in Javascript


JavaScript Module pattern provides a way to wrap public, private methods (and variable) into a single entity and exposing only the public members to the world outside of module. This allows faster namespace resolution, avoid collision of the methods/variables with other global APIs since the namespace isn't populated with all many functions, and obviously provides cleaner code.

CalcModule = (function(){
            var mem = new Array(); //private variable

            var storeInMemory = function(val) {  //private function
                mem.push(val);
            };

            var add = function(a, b) {
                        var result = a + b;
                        storeInMemory(result); //call to private function
                        return result;
                    };

            var sub = function(a, b) {
                        var result = a - b;
                        storeInMemory(result); //call to private function
                        return result;
                    };

            var retrieveFromMemory = function() {
                        return mem.pop();
                    };

            return {
                add: add,
                sub: sub,
                popMemory: retrieveFromMemory
            };
})();

Instead we define all the functions public or not in the same way, and then in the return statement create a new object and add properties to it.

Advantages of Revealing Module pattern in Javascript
1. Consistent coding style inside the module for both private and public members.
2. Better control on the name of the public API, i.e., if it is required to change the name of add()         method to addition(), all we need to do is change the name in the return statement without effecting    the function name inside the module.
3.Control on what to make public, just adding/removing the properties in return statement is sufficient.
4.As always, cleaner code.

reference : http://viralpatel.net/blogs/javascript-module-pattern/

No comments:

Post a Comment

Comments Welcome