Last active
August 29, 2015 14:20
-
-
Save hoodwink73/03f0551bfd060b88bde6 to your computer and use it in GitHub Desktop.
A quick revision of the infamous Module Pattern
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
// MAKING GLOBALS EXPLICIT | |
// ----------------------- | |
// large projects may make finding globals | |
// inside a module confusing | |
// to spot globals easily, lets just | |
// pass it as arguments | |
(function ($, YAHOO) { | |
// now have access to globals jQuery (as $) and YAHOO in this code | |
}(jQuery, YAHOO)); | |
// REUSING MODULES | |
// Store whatever the module has to offer in a | |
// global and it can be used by some code in **some other file** | |
var MODULE = (function (GLOBAL) { | |
// the object which will be exported | |
// as the interface for this module | |
// public methods will be declared on this | |
var MODULE = {}; | |
// world changing code | |
// help captive in closure | |
MODULE.missionMars = function () {}; | |
// more world changing mission | |
// that can be accessed | |
// other files which gets loaded | |
// after this file can access this | |
// module as its stored in the global | |
// scope | |
return MODULE; | |
})(GLOBAL); | |
// AUGMENTATION - EXTENDING EXISTING MODULE | |
// To extend a module from a different file | |
// the module has to be loaded before the | |
// the code tries to extend it. THAT NEED | |
// NOT BE THE CASE | |
// LOOSE AUGMENTATION - We can create flexible multi-part modules | |
// that can load themselves in any order | |
var MODULE = (function (my) { | |
// add capabilities... | |
return my; | |
}(MODULE || {})); | |
// TIGHT AUGMENTATION - OVERIDDING EXISTING MODULES | |
// Yes, you heard that write, what if we want to use | |
// a module from another file and override some chosen | |
// methods. What if we want to use an existing method defined on | |
// the module in the new file **while initializing it (things | |
// would be file at runtime since the module as a whole will be | |
// defined)** | |
var MODULE = (function (my) { | |
var old_moduleMethod = my.moduleMethod; | |
my.moduleMethod = function () { | |
// method override, has access to old through old_moduleMethod... | |
}; | |
return my; | |
}(MODULE)); | |
// Major actions with a module are Import, Export, Extend, Override | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment