As we’ll see in the next paragraphs, the module pattern depends heavily in the use of anonymous closures. Anonymous closures are created by introducing an anonymous function which is executed immediately. The code run inside that function ensures privacy and state throughout the lifetime of the app. Notice also that this function will typically return an object which can be used to access that internal state. The following snippet illustrates the previous points:
As you can see, we’re defining and invoking an anonymous function. The invocation part is really important. If you miss the () operator, you’ll end up injecting a function in the current scope (which, in the previous example, is the global scope). In other words, we would end up polluting the global namespace, which is precisely the problem we’re trying to solve. As I said, the execution of the function ends up creating a closure. Since I had the good sense of using the var keyword when I introduced the someValue variable, I’ve ended up creating a local variable and it will only be available to code defined within that anonymous function (this is the privacy advantage I’ve mentioned before). The same thing happens to the internal printValue function: it’s only available to other code written within the anonymous function.
You’ve also noticed that the anonymous function returns an object with a single property. In practice, this is known exporting a value from the module. In this case, the single property of the exported object is a reference to the private printValue defined within the anonymous function and that means that we can call that function through the obj reference (as illustrated in the last line).
The previous code shows how to create a basic module, but we still have an additional aspect to discuss before wrapping up the modules: what about dependencies? I’ll leave that topic to a future post. Stay tuned for more.