3

The revealing module pattern in JavaScript explained

 3 years ago
source link: https://pawelgrzybek.com/the-revealing-module-pattern-in-javascript-explained/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The revealing module pattern in JavaScript explained

Published: 2021.01.06 | 1 minutes read

Encapsulation, or information hiding in other words, is one of the core characteristics of every module system. A well-designed module should export only a simple interface and keep the irrelevant logic private and inaccessible.

Before ECMAScript 2015, JavaScript language was lacking an official module system. Lack of namespacing and protecting against polluting the global environment forced developers to design many solutions for this problem. One of them is the revealing module pattern. Have a look at the example below.

const myModule = (() => {
  const privateStuff = "private stuff";
  const publicStuff = "public stuff";

  return {
    publicStuff,
  };
})();

console.log(myModule.privateStuff); // undefined
console.log(myModule.publicStuff); // public stuff

Lexical scope of JavaScript functions keeps data that shouldn’t be accessible by the user private (privateStuff). Immediately Invoked Function Expression (or IIFE, pronounced “iffy”) exports only public-facing API (publicStuff) and assigns it to the myModule variable.

Quick and informative. Hopefully, you learned a thing. Until next time 👋

If you liked this article, please share it on Twitter.

Copyright © 2021 Pawel Grzybek

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK