A Week in JavaScript Patterns: The Module
The Module is a brilliant design pattern which demonstrates the elegance of the JavaScript language by exploiting closure (one of JavaScript’s most powerful features) to create private members. The Module makes use of Self-invocation making it useful as an application wrapper.
This pattern was originally discovered and named by Douglas Crockford.
Motivation
By default, there is no natural data hiding functionality in the JavaScript language. As developers push the limits by continually creating more complex applications, the need for private object members becomes increasingly apparent.
Implementation
Modules are simply a standard self-invoking function who’s return value is an object of properties and methods which serve as a public API. In the example below, foo.bar is not being set to the value of the anonymous function but rather the object that is returned by the anonymous function.
foo.bar = (function () {
var baz = function () {};
var bif = function () {};
return {
'thud' : function () {},
'grunt' : function () {}
};
})();
foo.bar now has an object as its value which contains two methods: thud and grunt. baz and bif are not available publicly, however thud and grunt still have direct access to them through closure.
Understanding Closure
Closure is a byproduct of functional programming whereby inner functions have access to local variables defined within an outer function, even after the outer function has returned.
There are several important facts to understand:
- Functions can contain other functions, just like any other variable. These are inner functions.
- Anything not returned by the outer function will not be directly available, however it still exists and is available to any inner functions that shared the same scope.
Conclusion
With the ability to implement public and private members in an API, developers now have the ability to create robust APIs in JavaScript. This allows developers to create powerful applications while exposing only what is necessary to make it function.
The Module also introduces the concept of closure. This is an extremely powerful concept of JavaScript which is a result of its functional nature. Future patterns in this series will make heavy use of closure in order to better understand its power and to show the various ways it can be applied.
Posts in this Series
- Sunday: Self-invocation
- Monday: Load Time Configuration
- Tuesday: The Module
- Wednesday: Lazy Function Definition