Skip to content

Instantly share code, notes, and snippets.

@afshinator
Last active August 29, 2015 14:01
Show Gist options
  • Save afshinator/31460b8e4eafc1eeced5 to your computer and use it in GitHub Desktop.
Save afshinator/31460b8e4eafc1eeced5 to your computer and use it in GitHub Desktop.
Javascript Module Patterns - some examples for comparison and contrast
// This one is from
// http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript
var addyRevealingModule = (function () {
var privateVar = "Joe Schmoe",
publicVar = "Howdy stranger!";
function privateFunction() {
console.log( "Name:" + privateVar );
}
function publicSetName( strName ) {
privateVar = strName;
}
function publicGetName() {
privateFunction();
}
// Reveal public pointers to
// private functions and properties
return {
setName: publicSetName,
greeting: publicVar,
getName: publicGetName
};
})();
// The module pattern I use a lot
//
var myModule = (function ($, my) {
// private (to this module) vars
var anArray = [],
someText = "whatever";
// public vars
my.greeting = "hello";
function privateFunction() {
console.log( "whatever" );
}
my.publicFunction = function(){
};
// Immediately executing function
my.ImmedExecuting = (function() {
var anotherFx = function() {
var width = 960;
function aMethod( title ) {
// do something
}
};
return {
objMethod1 : aMethod
};
})();
return my;
}(jQuery, myModule || {}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment