I remember that a few years back, I found it pretty hard to wrap my head around closures in Javascript. After months of struggling with them with readings, exercises, and tutorials, what helped me get a handle on them was using them in my day-to-day work. In my web and app development, I started writing immediately-invoking function expressions that used closures. My initial expressions simply had a getter and a setter, as in the function below:
var myFunc = (function() {
let num = 0;
return {
get:function() {
return num;
},
set:function(x) {
num = x;
}
};
})();
And over time I ended up building out more complex expressions.
I later found out that I was routinely using what is known as the module design pattern. As I continued to built out variations of this pattern, I found that it became quite useful in compartmentalizing the numerous components in web interactives and in my Cordova app, which now has a fairly large codebase.
Last night I started thinking how I might teach the module design pattern to someone relatively new to Javascript. I wrote a quick tutorial on the pattern, which is now available in CodeX. Feel free to give it a read - I hope you find it helpful.
https://medium.com/codex/put-the-javascript-module-design-pattern-to-work-41396c577084
Top comments (1)
Nice!