JavaScript — Module pattern
Vanilla JavaScript Module Pattern
In this article I am going to focus on different flavours of the Module Pattern written in plain JavaScript with no dependencies.
If you require more complex module systems, you can look into:
- CommonJS Modules (server, Node.js) — or
- Asynchronous Module Definition (AMD, browser)
Before using them take some time to evaluate if they help to solve your specific scenario as they come with some extra overhead. You can start looking here or the links at the end. Writing Modular JavaScript With AMD, CommonJS & ES Harmony
This pattern gets more important as your team or JavaScript code base grows in size. It uses previous patterns — Namespaces — Immediate functions — Encapsulation.
Basic form (using literal notation)
Basic form (using an object)
We achieve encapsulation by using a closure (Immediate Function) and deciding what properties are visible to the parent scope. As we saw, closures store the local variables scope at the time of execution. This is when we call the immediate function.
Advanced form (using parameter injection)
Sometimes we need an initial state or dependencies. We can use the Immediate Function parameters to achieve that.