๐Ÿ“šย Reference


๐Ÿ“œย Chapter


โ€ฃ

Closure

IIFE (Immediately Invoked Function Expression)

Singleton pattern


์˜ˆ์‹œ


// Singleton.js
const Singleton = (function() {
  let instance;

  function createInstance() {
    // ์‹ค์ œ ๊ฐ์ฒด ์ƒ์„ฑ ๋กœ์ง
    const object = new Object("This is the singleton object");
    return object;
  }

  return {
    getInstance: function() {
      if (!instance) {
        instance = createInstance();
      }
      return instance;
    }
  };
})();

// ์‚ฌ์šฉ ์˜ˆ์‹œ
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();

console.log(instance1 === instance2); // true
console.log(instance1); // Object { ... }
console.log(instance2); // Object { ... }