JavaScript modules are the most used design pattern to keep your code separate from your components which provides loose coupling to your code.
Modules are JavaScript classes, which provides protection of states and behaviours from being accessed by other classes. The module pattern allows for public and private access levels.
This is how the code looks like:
(function() {
// declare private variables and/or functions
return {
// declare public variables and/or functions
}
})();
Here we have to instantiate the private variables and functions before returning our object. Code outside of our function is unable to access these private variables since it is not in the same scope.
Let's take one more example
var HTMLChanger = (function() {
var contents = 'contents'
var changeHTML = function() {
var element = document.getElementById('attribute-to-change');
element.innerHTML = contents;
}
return {
callChangeHTML: function() {
changeHTML();
console.log(contents);
}
};
})();
HTMLChanger.callChangeHTML(); // Outputs: 'contents'
console.log(HTMLChanger.contents); // undefined
Notice that callChangeHTML
binds the returned object and can be referenced within the HTMLChanger
namespace. However, when outside the module, contents can't be accessed.
The only disadvantage of Module pattern is unable to reference the private methods. This can pose unit testing challenges. Similarly, the public behaviours are non-overridable.