Module And Revealing Module Design Patterns In Javascript
Hello everybody,
today I want to propose you interesting comparison of two design patterns in javascript. As you probably know, javascript doesn't have idea of public and private members. So in order to implement them some tricks are used. That is module and "revealing module".
Take a look at samples of them:
Module |
Revealing module |
var md = ( function(){ var privateMember = “private”; return { publicMember : “publicMember” }; } )(); |
var md = ( function(){ var privateMember = “private”; var publicMember = “publicMember”; return { publicMember : “publicMember” }; } )(); |
The difference is where are members declared. In module all private members are declared inside of the function, and public members inside of return object. While revealing module has all of it's members declared inside of the function, and then returned only public members.
One of the common critisizm of revealing module pattern is challenge in distinguishing from declaration which member is public and which private. One of the common conventions is to prefix private members with prefix _. For example
var md = ( function(){
var _privateMember = “private”;
var publicMember = “publicMember”;
return {
publicMember : “publicMember”
};
}
)();