๐ย Reference
๐ย Chapter
โฃ
IIFE (Immediately Invoked Function Expression)
// 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 { ... }
Singleton
๋ณ์๋ ์ฆ์ ์คํ ํจ์ ํํ์(IIFE: Immediately Invoked Function Expression)์ ํตํด ์์ฑ๋๋ค.
instance
๋ณ์๋ ํด๋ก์ ์ ์ํด getInstance
๋ฉ์๋ ๋ด๋ถ์์๋ง ์ ๊ทผ ๊ฐ๋ฅํ๋ค.getInstance
๋ฉ์๋๊ฐ ํธ์ถ๋ ๋, instance
๊ฐ ์์ง ์กด์ฌํ์ง ์์ผ๋ฉด createInstance
ํจ์๋ฅผ ํธ์ถํ์ฌ ๊ฐ์ฒด๋ฅผ ์์ฑํ๋ค.Singleton.getInstance()
๋ฅผ ๋ช ๋ฒ ํธ์ถํ๋ ๋์ผํ ๊ฐ์ฒด๋ฅผ ๋ฐํํ๊ฒ ๋์ด ์ฑ๊ธํค ํจํด์ ์์น์ ์งํฌ ์ ์๋ค.