The Revealing Module pattern

The Revealing Module pattern is a pattern used to encapsulate some private logic and then expose a public API. There are a few adaptations of this pattern, but usually it is expressed via an Immediately Invoked Function Expression (IIFE) that returns an object literal containing the public methods and properties:

const myModule = (() => {
const privateFoo = 1;
const privateBaz = 2;

// (Private Initialization Logic goes here)

return {
publicFoo() {},
publicBaz() {}
};
})();

Any functions returned by the IIFE will form a closure around their respective scopes, meaning that they will continue to have access to the private scope.

An example of a real-world Revealing Module would be this simple DOM Component that contains logic for rendering a notification to users:

const notification = (() => {

const d = document;
const container = d.body.appendChild(d.createElement('div'));
const message = container.appendChild(d.createElement('p'));
const dismissBtn = container.appendChild(d.createElement('button'));

container.className = 'notification';

dismissBtn.textContent = 'Dismiss!';
dismissBtn.onclick = () => {
container.style.display = 'none';
};

return {
display(msg) {
message.textContent = msg;
container.style.display = 'block';
}
};
})();

The notification variable in the outer scope will refer to the object returned by the IIFE, meaning we have access to its public API:

notification.display('Hello user! Something happened!');

The Revealing Module pattern is especially useful in scenarios where you need to have a delineation between private and public, where you have specific initialization logic, and where, for whatever reason, your abstraction does not suit more object-oriented patterns (Class or Constructor patterns).

Before the existence of class definitions and #private fields, the Revealing Module pattern was the only easy way to emulate real privacy. As such, it has somewhat fallen out of favor. Some programmers still make use of it but, usually, only due to aesthetic preferences.

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

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