Skip to content

Instantly share code, notes, and snippets.

@Omar-Gonzalez
Created July 13, 2017 03:11
Show Gist options
  • Save Omar-Gonzalez/febbc07e18231d9bb0bdabfe632e3453 to your computer and use it in GitHub Desktop.
Save Omar-Gonzalez/febbc07e18231d9bb0bdabfe632e3453 to your computer and use it in GitHub Desktop.
JS Module Pattern
//The module pattern heavily uses closures
var global = 'a global';
(function (){
//All vars and functions are in this scope only
//Still mantains access to all globals
console.log(global) //prints 'a global'
}());
//Importing globals
(function (){
//All vars and functions are in this scope only
//Still mantains access to all globals
//now you ahave access to someVar
console.log(someVar)
}(someVar));
//Module Export
var MODULE = (function(){
var module = {}
var privateVar = 'Omar';
function privateMethod(){
}
module.publicProperty = 1;
module.publicMethod = function(){
console.log(privateVar)
}
return module;
}());
MODULE.publicMethod();
console.log(MODULE.publicProperty);
//Augmentation
//Augmentation
var MODULE = (function (m){
m.newMethod = function (){
console.log('new method');
}
return m;
}(MODULE));
MODULE.newMethod();
//Loose Augmentation
//load scripts asynchronously
//Cannot override module properties safely
var MODULE = (function (my) {
// add capabilities...
return my;
}(MODULE || {}));
//Tight Augmentation
var MODULE = (function (my) {
var oldModuleMethod = my.moduleMethod;
my.moduleMethod = function () {
// method override, has access to old through oldModuleMethod...
};
return my;
}(MODULE));
//Sub Modules, go crazy
MODULE.sub = (function(){
var my = {};
return my;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment