Adding Modules to a Namespace

Many other programming languages have special syntax for creating modules and packaging them together. ES5 does not. Instead, you can get the same kind of organization using objects.

You can use objects to associate any kind of data with a key name. In fact, this is precisely how you will organize your modules. Specifically, you will use a single object as the namespace for your CoffeeRun application. This namespace is where individual modules register themselves, which makes them available for use by your other application code.

There are three steps to using IIFEs to register modules in a namespace:

  1. Get a reference to the namespace, if it exists.

  2. Create the module code.

  3. Attach your module code to the namespace.

Let’s see what that looks like in practice. Update your IIFE in datastore.js as shown. We will explain the code after you enter it.

(function (window) {
  'use strict';
  // Code will go here
  var App = window.App || {};

  function DataStore() {
    console.log('running the DataStore function');
  }

  App.DataStore = DataStore;
  window.App = App;
})(window);

In the body of the IIFE, you declared a local variable named App. If there is already an App property of the window, you assign the local App to it. If not, the label App will refer to a new, empty object, represented by {}. The || is the default operator, otherwise known as the logical or operator. It can be used to provide a valid value (in this case, {}) if the first choice (window.App) has not yet been created.

Each of your modules will do this same check. It is like saying “Whoever gets there first: Go ahead and start a new object. Everyone else will use that object.”

Next, you declared a function named DataStore. You will add more code to this function shortly.

Finally, you attached DataStore to the App object and reassigned the global App property to your newly modified App. (If it did not already exist and you had to create it as an empty object, you must attach it.)

Save your files and switch over to the browser. Open the DevTools, click on the tab for the console, and call your DataStore function with the following code:

App.DataStore();

DataStore runs and prints some text to the console (Figure 8.7).

Figure 8.7  Running the App.DataStore function

Running the App.DataStore function

Notice that you did not need to write window.App.DataStore();. This is because the window object is the global namespace. All of its properties are available to any JavaScript code you write, including in the console.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.251.128