Modules

There are other code patterns which leverage the power of closure but which do not on the surface appear to be about callbacks. Let’s examine the most powerful of them: the module.

  1. function foo() {
  2. var something = "cool";
  3. var another = [1, 2, 3];
  4. function doSomething() {
  5. console.log( something );
  6. }
  7. function doAnother() {
  8. console.log( another.join( " ! " ) );
  9. }
  10. }

As this code stands right now, there’s no observable closure going on. We simply have some private data variables something and another, and a couple of inner functions doSomething() and doAnother(), which both have lexical scope (and thus closure!) over the inner scope of foo().

But now consider:

  1. function CoolModule() {
  2. var something = "cool";
  3. var another = [1, 2, 3];
  4. function doSomething() {
  5. console.log( something );
  6. }
  7. function doAnother() {
  8. console.log( another.join( " ! " ) );
  9. }
  10. return {
  11. doSomething: doSomething,
  12. doAnother: doAnother
  13. };
  14. }
  15. var foo = CoolModule();
  16. foo.doSomething(); // cool
  17. foo.doAnother(); // 1 ! 2 ! 3

This is the pattern in JavaScript we call module. The most common way of implementing the module pattern is often called “Revealing Module”, and it’s the variation we present here.

Let’s examine some things about this code.

Firstly, CoolModule() is just a function, but it has to be invoked for there to be a module instance created. Without the execution of the outer function, the creation of the inner scope and the closures would not occur.

Secondly, the CoolModule() function returns an object, denoted by the object-literal syntax { key: value, ... }. The object we return has references on it to our inner functions, but not to our inner data variables. We keep those hidden and private. It’s appropriate to think of this object return value as essentially a public API for our module.

This object return value is ultimately assigned to the outer variable foo, and then we can access those property methods on the API, like foo.doSomething().

Note: It is not required that we return an actual object (literal) from our module. We could just return back an inner function directly. jQuery is actually a good example of this. The jQuery and $ identifiers are the public API for the jQuery “module”, but they are, themselves, just a function (which can itself have properties, since all functions are objects).

The doSomething() and doAnother() functions have closure over the inner scope of the module “instance” (arrived at by actually invoking CoolModule()). When we transport those functions outside of the lexical scope, by way of property references on the object we return, we have now set up a condition by which closure can be observed and exercised.

To state it more simply, there are two “requirements” for the module pattern to be exercised:

  1. There must be an outer enclosing function, and it must be invoked at least once (each time creates a new module instance).

  2. The enclosing function must return back at least one inner function, so that this inner function has closure over the private scope, and can access and/or modify that private state.

An object with a function property on it alone is not really a module. An object which is returned from a function invocation which only has data properties on it and no closured functions is not really a module, in the observable sense.

The code snippet above shows a standalone module creator called CoolModule() which can be invoked any number of times, each time creating a new module instance. A slight variation on this pattern is when you only care to have one instance, a “singleton” of sorts:

  1. var foo = (function CoolModule() {
  2. var something = "cool";
  3. var another = [1, 2, 3];
  4. function doSomething() {
  5. console.log( something );
  6. }
  7. function doAnother() {
  8. console.log( another.join( " ! " ) );
  9. }
  10. return {
  11. doSomething: doSomething,
  12. doAnother: doAnother
  13. };
  14. })();
  15. foo.doSomething(); // cool
  16. foo.doAnother(); // 1 ! 2 ! 3

Here, we turned our module function into an IIFE (see Chapter 3), and we immediately invoked it and assigned its return value directly to our single module instance identifier foo.

Modules are just functions, so they can receive parameters:

  1. function CoolModule(id) {
  2. function identify() {
  3. console.log( id );
  4. }
  5. return {
  6. identify: identify
  7. };
  8. }
  9. var foo1 = CoolModule( "foo 1" );
  10. var foo2 = CoolModule( "foo 2" );
  11. foo1.identify(); // "foo 1"
  12. foo2.identify(); // "foo 2"

Another slight but powerful variation on the module pattern is to name the object you are returning as your public API:

  1. var foo = (function CoolModule(id) {
  2. function change() {
  3. // modifying the public API
  4. publicAPI.identify = identify2;
  5. }
  6. function identify1() {
  7. console.log( id );
  8. }
  9. function identify2() {
  10. console.log( id.toUpperCase() );
  11. }
  12. var publicAPI = {
  13. change: change,
  14. identify: identify1
  15. };
  16. return publicAPI;
  17. })( "foo module" );
  18. foo.identify(); // foo module
  19. foo.change();
  20. foo.identify(); // FOO MODULE

By retaining an inner reference to the public API object inside your module instance, you can modify that module instance from the inside, including adding and removing methods, properties, and changing their values.

Modern Modules

Various module dependency loaders/managers essentially wrap up this pattern of module definition into a friendly API. Rather than examine any one particular library, let me present a very simple proof of concept for illustration purposes (only):

  1. var MyModules = (function Manager() {
  2. var modules = {};
  3. function define(name, deps, impl) {
  4. for (var i=0; i<deps.length; i++) {
  5. deps[i] = modules[deps[i]];
  6. }
  7. modules[name] = impl.apply( impl, deps );
  8. }
  9. function get(name) {
  10. return modules[name];
  11. }
  12. return {
  13. define: define,
  14. get: get
  15. };
  16. })();

The key part of this code is modules[name] = impl.apply(impl, deps). This is invoking the definition wrapper function for a module (passing in any dependencies), and storing the return value, the module’s API, into an internal list of modules tracked by name.

And here’s how I might use it to define some modules:

  1. MyModules.define( "bar", [], function(){
  2. function hello(who) {
  3. return "Let me introduce: " + who;
  4. }
  5. return {
  6. hello: hello
  7. };
  8. } );
  9. MyModules.define( "foo", ["bar"], function(bar){
  10. var hungry = "hippo";
  11. function awesome() {
  12. console.log( bar.hello( hungry ).toUpperCase() );
  13. }
  14. return {
  15. awesome: awesome
  16. };
  17. } );
  18. var bar = MyModules.get( "bar" );
  19. var foo = MyModules.get( "foo" );
  20. console.log(
  21. bar.hello( "hippo" )
  22. ); // Let me introduce: hippo
  23. foo.awesome(); // LET ME INTRODUCE: HIPPO

Both the “foo” and “bar” modules are defined with a function that returns a public API. “foo” even receives the instance of “bar” as a dependency parameter, and can use it accordingly.

Spend some time examining these code snippets to fully understand the power of closures put to use for our own good purposes. The key take-away is that there’s not really any particular “magic” to module managers. They fulfill both characteristics of the module pattern I listed above: invoking a function definition wrapper, and keeping its return value as the API for that module.

In other words, modules are just modules, even if you put a friendly wrapper tool on top of them.

Future Modules

ES6 adds first-class syntax support for the concept of modules. When loaded via the module system, ES6 treats a file as a separate module. Each module can both import other modules or specific API members, as well export their own public API members.

Note: Function-based modules aren’t a statically recognized pattern (something the compiler knows about), so their API semantics aren’t considered until run-time. That is, you can actually modify a module’s API during the run-time (see earlier publicAPI discussion).

By contrast, ES6 Module APIs are static (the APIs don’t change at run-time). Since the compiler knows that, it can (and does!) check during (file loading and) compilation that a reference to a member of an imported module’s API actually exists. If the API reference doesn’t exist, the compiler throws an “early” error at compile-time, rather than waiting for traditional dynamic run-time resolution (and errors, if any).

ES6 modules do not have an “inline” format, they must be defined in separate files (one per module). The browsers/engines have a default “module loader” (which is overridable, but that’s well-beyond our discussion here) which synchronously loads a module file when it’s imported.

Consider:

bar.js

  1. function hello(who) {
  2. return "Let me introduce: " + who;
  3. }
  4. export hello;

foo.js

  1. // import only `hello()` from the "bar" module
  2. import hello from "bar";
  3. var hungry = "hippo";
  4. function awesome() {
  5. console.log(
  6. hello( hungry ).toUpperCase()
  7. );
  8. }
  9. export awesome;
  1. // import the entire "foo" and "bar" modules
  2. module foo from "foo";
  3. module bar from "bar";
  4. console.log(
  5. bar.hello( "rhino" )
  6. ); // Let me introduce: rhino
  7. foo.awesome(); // LET ME INTRODUCE: HIPPO

Note: Separate files “foo.js” and “bar.js” would need to be created, with the contents as shown in the first two snippets, respectively. Then, your program would load/import those modules to use them, as shown in the third snippet.

import imports one or more members from a module’s API into the current scope, each to a bound variable (hello in our case). module imports an entire module API to a bound variable (foo, bar in our case). export exports an identifier (variable, function) to the public API for the current module. These operators can be used as many times in a module’s definition as is necessary.

The contents inside the module file are treated as if enclosed in a scope closure, just like with the function-closure modules seen earlier.