Redoing our IIFE module in the modern way

The key concept in modules is that you'll have separate files, each of which will represent a module. There are two complementary concepts: importing and exporting. Modules will import the features they require from other modules, which must have exported them so that they are available.

First, let's look at the equivalent of our counter module from the previous section, and then comment on the extra features we can use:

// Source file: src/module_counter.1.js

/* @flow */

let name: string = "";
let count: number = 0;

let get = () => count;
let inc = () => ++count;
let toString = () => `${name}: ${get()}`;

/*
Since we cannot initialize anything otherwise,
a common pattern is to provide a "init()" function
to do all necessary initializations.
*/
const init = (n: string) => {
name = n;
};

export default { inc, toString, init }; // everything else is private

How would we use this module? Let's hold on the explanations about some internal aspects and answer that first.

To use this module in some other file from our application, we would write something as follows, with a new source file that imports the functions that our module exported:

// Source file: src/module_counter_usage.js

import myCounter from "module_counter";


/*
Initialize the counter appropriately
*/
myCounter.init("Clicks");


/*
The rest would work as before
*/
myCounter
.inc(); // 1
myCounter.inc(); // 2
myCounter.inc(); // 3
m
yCounter.toString(); // "Clicks: 3"

OK, so using this module to provide a counter isn't so different after all. The main difference with the IIFE version is that here, we cannot do an initialization. A common pattern to provide this is to export a init() function that will do whatever is needed. Whoever uses the module must, first of all, call init() to set things up properly.

There's no need to immediately call the init() function, as would happen with the IIFE version, and you could delay it until necessary. Also, the init() function could be called more times in order to reset the module. These possibilities provide extra functionality.
..................Content has been hidden....................

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