Modules are probably the most practical use of closures you can find in Javascript. By breaking your code up into separate files and "importing" what is needed, you tap into the super powers that closures give you. This notion is what I discussed in the first article of the series. In a nutshell, you can keep functions and variables "private" and inaccessible.
Traditional Object Oriented languages--for example C# and Java have access modifiers like private
, public
, and protected
to achieve a similar effect. For example, a public
method or property on a class can be accessed by other classes. This is very similar to exporting a function or variable in Javascript. (It's not a prefect comparison, but I see them as being two ways to reach a similar goal.)
The best way to understand is to study how the Javascript community converged around the module pattern as a way to isolate and protect code before modern approaches. Libraries like JQuery used the module pattern pattern to isolate and create an API for their users.
var mod = (function() {
//private function and variable
var status = 'is cool.';
function logName(name) {
return `${name} ${status}.`;
}
return logName;
})();
console.log(mod('Brian'));
We have an immediately invoked function that returns an anonymous function. It then spits back the logName
function. It's a pass through, called by mod instead of itself. logName
itself a single parameter in name
. The variable status can't be accessed or changed from outside of this script, meaning its "private."
A module like this simple one could be thrown into a script file on any HTML page. When it loads, it will attach the variable mod
to the window object, which can be used to call its function anywhere else on the page, even by other scripts.
The module pattern simple trick, albeit a powerful one. There are closures in the wild, all over the place! Once you understand the concept, they start revealing themselves all the time.
Note: There are differences between the module pattern and how ES6 modules work--as it's a built in feature of the language. However, for the most part it is still the same concept.
Latest comments (0)