rarely, especially for large projects we’re gonna to have all our code in one file, at first it’s easy enough to put your code in different files and smash them together in a specific order, however this quickly becomes unmanageable, using unknown pattern called “lose augmentation” we can actually take advantage of javascript asynchronous runtime environment.
to implement this pattern we are gonna a small piece of logic.
We’re gonna say if awesomeNewModule exist, then imported it, otherwise awesomeNewModule is simply new object:
var awesomeNewModule = (function(){
var exports={
foo:5,
bar:10
};
exports.helloMars = function(){
console.log("Hello Mars!");
};
exports.goodbye = function(){
console.log("Goodbye!");
}
return exports;
}(awesomeNewModule || {}));
and up here since we’re using exports keyword, we’re gonna say that awesomeNewModule is exports within a function, now all these values of exports {foo:5, bar:10} will either get assigned to the empty object {} if this was the first file or will get assigned and extend awesomeNewModule if this file was loaded after the module had already been created.
var awesomeNewModule = (function(exports){
var exports={
foo:5,
bar:10
};
exports.helloMars = function(){
console.log("Hello Mars!");
};
exports.goodbye = function(){
console.log("Goodbye!");
}
return exports;
}(awesomeNewModule || {}));
one of the important thing to keep in mind is that if awesomeNewModule is already exist, then you should make sure that none of these keys {foo:5, bar:10} already exist in awesomeNewModule as well none of these methods: exports.helloMars , exports.goodbye
if so, whatever file is loaded last will override any methods or values that were named the same in previous files.
for this reason you can’t share values across the modules, if any aspect of one module depends on another then you can’t safe we depend on those values, but at the end of the day the whole point of writing module or code is that you split your app in pieces that don’t depend on each other, this way if one module introduces a breaking error to the application, doesn’t affect the rush of the code.
Additionally there are ways to safe cards to make sure that one module doesn’t override patterns or methods created from another modules.
source: treehouse workshop about basics of Module Pattern in javascript