Archive

Archive for the ‘javascript’ Category

Javascript : modular pattern

February 16, 2014 Leave a comment

While writing javascript code as a beginner we just write

function hello(){
alert('hello world');
}

but some problems occur with this approach, when we include multiple js files. All the variables which are declared outside any function will be treated as global and can be accessed from any function. And all the functions in all the js files are local to each other that means we can call any function from any js file, there is no concept of private function or we can not hide any function from being called.

With Javascript modular pattern we can avoid all these.

In this pattern we assign an anonymous function to global variable and all the functions declared inside can be called by using the variable name and the function name.

var app = (function (){

})();

Here app is the global variable and an anonymous function is assigned to it.

var app = (function (){
    return {
       publicFun : function(){
              alert('public function');
             }
    };
})();

Declared a function with name publicFun, to access this function we have to call with global variable name app.publicFun(); and it will alert with “public function”.

Private functions: Whatever the functions we returned from the anonymous function can be accessed by using app global variable.

If we declare any function before return function, that will be called as local function and can not accessed with app variable.

var app = (function (){
    function privateFun(){
             alert('private function');
    }
    return {
       publicFun : function(){
              alert('public function');
             }
    };
})();

If we call app.privateFun(); will give an error : TypeError: app.privateFun is not a function

So these private functions can not be accessed out side of the anonymous block. But we can call these in side any other publicĀ  function.

var app = (function (){
    function privateFun(){
             alert('private function');
    }
    return {
       publicFun : function(){
              privateFun();
              alert('public function');
             }
    };
})();

Now app.publicFun() will internally call private function and will get private function alert followed by public function. Thanks for reading, hope you enjoyed it.

Advertisements
Categories: javascript