This pattern is used to mimic classes in conventional software engineering and focuses on public and private access to methods & variables. The module pattern strives to improve the reduction of globally scoped variables, thus decreasing the chances of collision with other code throughout an application.
- Brian Cray
- Cleaner approach for developers
- Supports private data
- Less clutter in the global namespace
- Localization of functions and variables through closures
- Private methods are unaccessible.
Some people say that this leads to the inability of unit testing but more often than not, if you’re questioning the integrity of a function, it should probably be engineered in such a fashion that exposes the utility of that function publicly, thus making it testable. Given the adaptation of the module pattern by jQuery and their everyday use of QUnit to automate testing, this bullet point isn’t really relevant but still listed for documentation purposes.
- Private methods and functions lose extendability since they are unaccessible (see my comment in the previous bullet point).
|1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28||
Another example of the module pattern that exposes the module a little differently and makes use of a shared private cache. This method encourages more of an object creation approach where we can optimize performance by being efficient with shared storage.
|1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25||
Other Common JS Patterns
- 8/22: Added an additional example based off of Ben Truyman’s comment below