Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rizalp/5500889 to your computer and use it in GitHub Desktop.
Save rizalp/5500889 to your computer and use it in GitHub Desktop.
JavaScript: Anonymous Functions And The Module Pattern
//For example, the following definition would result in three global variables and two global functions:
var name = 'Chris';
var age = '34';
var status = 'single';
function createMember(){
// [...]
}
function getMemberDetails(){
// [...]
}
// Any other script on the page that has a variable named status could cause trouble. If we wrap all of this in a name such as myApplication, then we work around that issue:
var myApplication = function(){
var name = 'Chris';
var age = '34';
var status = 'single';
function createMember(){
// [...]
}
function getMemberDetails(){
// [...]
}
}();
//This, however, doesn't do anything outside of that function. If this is what you need, then great. You may as well discard the name then:
(function(){
var name = 'Chris';
var age = '34';
var status = 'single';
function createMember(){
// [...]
}
function getMemberDetails(){
// [...]
}
})();
//If you need to make some of the things reachable to the outside, then you need to change this. In order to reach createMember() or getMemberDetails(), you need to return them to the outside world to make them properties of myApplication:
//This is called a module pattern or singleton.
var myApplication = function(){
var name = 'Chris';
var age = '34';
var status = 'single';
return{ //need to switch syntaxes to make functions or variables available to the outside world.
createMember:function(){
// [...]
},
getMemberDetails:function(){
// [...]
}
}
}();
//have to call it preceded by the myApplication name
// myApplication.createMember() and
// myApplication.getMemberDetails() now works.
// I prefer simply to return pointers to the elements that I want to make public.
// this one is called revealing module pattern
// http://christianheilmann.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/
var myApplication = function(){
var name = 'Chris';
var age = '34';
var status = 'single';
function createMember(){
// [...]
}
function getMemberDetails(){
// [...]
}
return{
create:createMember,
get:getMemberDetails
}
}();
//myApplication.get() and myApplication.create() now work.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment