dungarian
dungarian

Reputation: 237

Can revealing module pattern be done without IIFE like this and serve same purpose?

My understanding of revealing module pattern is as follows:

CODE #1

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

iifeModulePattern.methodForPublic();

So far I hope I'm not wrong. My question is:

  1. Won't the following Code #2 serve same purpose?
  2. If it does, why is Code #1 popular than Code #2?
  3. If it doesn't, what's the difference?

CODE #2

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

modulePattern().methodForPublic();

I won't store "secret" codes (like passwords) in this way. The above codes are just examples.

Upvotes: 0

Views: 184

Answers (1)

Thomas
Thomas

Reputation: 12637

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

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

console.log("The basic IIFE.");
console.log("");

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

for (let i = 0; i < 5; ++i) {
  console.log("modulePattern().next()", i, modulePattern().next());
}
console.log("Kinda pointless this way, ain't it? Everytime, the sequence starts all over.");
console.log("");

const instance1 = modulePattern();
const instance2 = modulePattern();
for (let i = 0; i < 10; ++i) {
  console.log("instance1.next()", i, instance1.next());
  if (i & 1) {
    console.log("instance2.next()", i, instance2.next());
  }
}
console.log("This usage makes more sense.\nAnd the two instances progress independant of each other.");
.as-console-wrapper {top:0;max-height:100%!important}

Won't the following Code #2 serve same purpose?

Yes, No, maybe; it depends on how you use it.

If it doesn't, what's the difference?

iifeModulePattern is a singleton, modulePattern() is a factory.

If it does, why is Code #1 popular than Code #2?

What's the purpose of giving the factory a name, store it in a variable if all you'll ever do is to call it once, right here, right now?

Upvotes: 1

Related Questions