The module pattern is one of the amazing design patterns and I’d like to share some use cases and differences in the pattern, and why they’re important.
So, here is an example of this function.
We simply create an anonymous function and execute it immediately. All of the code that runs inside the function lives in a closure., which provides privacy and state throughout the lifetime of our application.
Luckily, our anonymous function provides an easy alternate. By passing globals as parameters to our anonymous function, we import them into our code, which is both cleaner and faster than implied globals.
Here’s an example:
Exporting our module
In order to export our module, you can simply assign this a variable that we can use to call our module methods.
Public methods in the module
Let’s first start with how to create public methods in our module. To expose our public method outside our module we return an object with the methods defined.
Private methods in the module
Here our privateMethod0 is private. Because our private methods are not returned they are not available outside of our module.
Accessing private methods
What if I need to access module’s private methods. Here is the trick: you can invoke private methods via public methods. Here is an example:
Extending our module
You can extend your existing module without touching it code. Here is an example.
In the above example, we have passed our jsModule to ModuleTwo, and added a new method extendedMethod to this. It will now return the object with this new method.
In the last, you can now access extendedMethod from our original module of jsModule.
Private Naming Convention