Is it possible to implement the revealing module pattern without using an IIFE in this way while still achieving the same goal

From my understanding, the concept of revealing module pattern can be demonstrated as follows:

SAMPLE #1

const iifeModulePattern = (function () {
  const secretSeed = 999; // ← hidden
  const logSecretCode = function(){console.log(secretSeed+1)};
  return {methodForPublic : logSecretCode};
})();

iifeModulePattern.methodForPublic();

As far as I know, I believe I am on the right track. Now, my question is:

  1. Wouldn't Sample #2 accomplish the same goal?
  2. If yes, why is Sample #1 more popular than Sample #2?
  3. If not, what sets them apart?

SAMPLE #2

const modulePattern = () => {
  const secretSeed = 999; // ← hidden
  const logSecretCode = function(){console.log(secretSeed+1)};
  return {methodForPublic : logSecretCode};
};

modulePattern().methodForPublic();

I want to clarify that these code snippets are only examples and not meant for storing actual sensitive information like passwords.

Answer №1

const immediateInvokeFunctionExpression = (function() {
  let value = 0; // private
  return {
    next: () => (value = 134775813 * value + 1) >>> 0
  };
})();

for (let i = 0; i < 5; ++i) {
  console.log("immediateInvokeFunctionExpression.next()", i, immediateInvokeFunctionExpression.next());
}

console.log("Understanding the concept of IIFE.");
console.log("");

const functionModulePattern = () => {
  let val = 0; // private
  return {
    next: () => (val = 134775813 * val + 1) >>> 0
  };
};

for (let i = 0; i < 5; ++i) {
  console.log("functionModulePattern().next()", i, functionModulePattern().next());
}
console.log("It might seem unnecessary this way as the sequence restarts each time.");
console.log("");

const inst1 = functionModulePattern();
const inst2 = functionModulePattern();
for (let i = 0; i < 10; ++i) {
  console.log("inst1.next()", i, inst1.next());
  if (i % 2 !== 0) {
    console.log("inst2.next()", i, inst2.next());
  }
}
console.log("Using multiple instances makes more sense.\nAnd these instances progress independently.");
.as-console-wrapper {top:0;max-height:100%!important}

Will a different Code #2 achieve the same result?

Yes, No, maybe; it relies on the usage scenario.

If not, what sets them apart?

immediateInvokeFunctionExpression
acts as a singleton, while functionModulePattern() is used as a factory method.

If so, why is Code #1 preferred over Code #2?

What's the point of naming and storing the factory in a variable when you intend to call it only once at the moment?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can a photo frame app be created using PhoneGap?

I'm looking to develop an application where I can capture a picture, crop the face of a person, and then embed this face into a frame. Is there a solution using PhoneGap for this task? Can anyone provide some ideas on how to get started? Thank you i ...

Create a placeholder for the module function

Update: Providing more specific details. Our team has developed a Github API wrapper extension and we are looking to test different use cases for it. However, we prefer not to use the API wrapper extension directly during testing and instead want to stub ...

My AJAX function is not functioning as intended

I'm currently developing a time management system for my workplace. As I was coding, I implemented a feature that allows users to configure the database details similar to the setup process in WordPress. Once the data is saved successfully, I aim to d ...

Create a captivating sliding effect on Windows 8 using a combination of CSS and JavaScript

I believe that using css3 alone can achieve this effect, but I'm struggling with understanding properties like 'ease' in css3. This is the progress I have made so far: http://jsfiddle.net/kwgy9/1/ The word 'nike' should slide to ...

Add a hovering effect to images by applying the absolute positioning property

On my React website, I am utilizing Tailwind CSS and I am attempting to showcase an image that has interactive elements. I want certain parts of the image to increase in size slightly when hovered over. My approach to achieving this was to save each part o ...

My component reference seems to have gone missing in angular2

Trying to load my Angular 2 app, I encountered this error: https://i.stack.imgur.com/FmgZE.png Despite having all the necessary files in place. https://i.stack.imgur.com/kj9cP.png Any suggestions on how to resolve this issue? Here is a snippet from ap ...

When a click event occurs, it returns either the element itself or one of its child elements,

Check out this HTML code snippet: <div class="list-group"> <a href="javascript:;" @click="showDetails(notification, $event)" class="list-group-item" v-for="notification in notifications" :key=& ...

Ajax is bypassing the success:function callback

Currently, I am working on implementing a login feature using ajax, HTML, and PHP. After debugging the PHP code, everything seems fine as it returns the necessary JSON variable for the ajax call. Below is the AJAX function I have created: $(document).read ...

Loading Bootstrap accordion content with AJAX only when clicked

Is there a way to load ajax content into an accordion only when it is active? This could help prevent unnecessary data loading. It would be helpful to have a spinner displayed while the content is loading. I've searched online but haven't found a ...

What is the method for accessing HTML tag data within a script?

Looking for a way to extract a specific substring from a given string: var str = `<ul class="errorlist"><li>Enter a valid email address.</li></ul>`; Is there a method to extract the following substring? 'Enter a valid email ...

What is causing this console to output twice?

My Objective: I aim to utilize Node.js to launch two child processes sequentially at a specific time, displaying their `stdout` as it streams, occasionally alternating between the two processes. The Desired Output: `Proc 1 log # 1` `Proc 1 log # 2` `Pr ...

Creating an executable JAR for your Next.js application: A step-by-step guide

Is there a way to ensure that my Next.js file can run seamlessly on any computer without the need for reinstallation of all modules? In my folder, nextjs-node, I have the following subfolders: components lib public node_modules page style package.json I ...

Discover the identities of elements that possess a specific attribute and class

I am looking to identify the ids of elements that have both the attribute data-test and the class myClass. In this scenario, the only element that meets both criteria is elem3: <input type="text" data-test="someValue" id="elem1" /> <input type=" ...

The functionality of the jQuery .on() method is not compatible with appending newly created DOM elements

While the jQuery .on() method is effective for handling 'click' events, it does not work with 'load' events. I am trying to add a class to a new DOM element after an AJAX load. Unfortunately, I am unable to edit the $('.nav a&apos ...

The formatter/render function in Angular Directive fails to refresh

Recently, I created a straightforward directive that converts minutes into a range slider while also displaying hours and minutes alongside. However, I encountered an issue where although moving the range slider updates the scope triggering Watch and Pars ...

Issue with reflect metadata in Next.js edge runtime causing functional problems

Currently, I am utilizing a package in my upcoming 13 app that incorporates reflect metadata. Unfortunately, during the next build process, an error occurs for which I haven't been able to find a solution. ../../eshop-sdk-js/node_modules/reflect-metad ...

Amplify encounters the "Failed to load resource: the server responded with a status of 400" issue

I encountered an error while using Amplify, although the build was completed successfully. Failed to load resource: the server responded with a status of 400 manifest.json:1 The system is functional in the local environment. Below is the Package.json scri ...

When scrolling, use the .scrollTop() function which includes a conditional statement that

As a newcomer to jQuery, I've been making progress but have hit a roadblock with this code: $(window).scroll(function(){ var $header = $('#header'); var $st = $(this).scrollTop(); console.log($st); if ($st < 250) { ...

Where can I find the JavaScript code that controls the button function?

Is there a method to identify the trigger that activates a button's specific action and page refresh, such as this example: <input type="submit" name="name" value="some value" id="mt1_main_btn" class="btn_next"> Simply copying the button does ...

Exploring the various possibilities of establishing multiple types of many-to-many relationships between two tables using Sequelize technology

Working with Sequelize in Node, I am dealing with Users and items. A user can interact with an item in various ways, such as voting or commending, which are distinct actions in this scenario. Initially, I considered having two separate many-to-many relati ...