Last active
August 29, 2015 14:01
-
-
Save afshinator/31460b8e4eafc1eeced5 to your computer and use it in GitHub Desktop.
Javascript Module Patterns - some examples for comparison and contrast
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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