Wednesday, March 2, 2016

Module patterns in javascript


Classic module pattern




ar classicModulePattern=(function(){
   
    var greeting={text: "hi"};

    return {
        sayHi: function(){
            console.log(greeting.text);
        }
    }   

})();


Modified module pattern 

The good thing about this module is that you can update it, you can remove and add attributes while in the classic module you will not be able to update the returned object.

var modifiedModulePattern= (function(){
    var publicAPI={
        sayHi: function(){
            publicAPI.sayBye();
        },
        sayBye:function(){
            console.log('Bye');
        }

    };
    return publicAPI;
})();

modifiedModulePattern.sayHi();


No comments:

Post a Comment