Front-end/JS
์๋ฐ์คํฌ๋ฆฝํธ ํด๋ก์ ํ์ฉ Closure private ๋ณ์, ๋ฉ์๋ ํ๋ด ๋ด๊ธฐ
ciocio
2021. 8. 28. 14:20
๐ Closure ํ์ฉ ๋ฐฉ๋ฒ
๋ํ์ ์ธ ์ด์ ์ค ํ๋๊ฐ, private ๋ณ์๋ ๋ฉ์๋๋ฅผ ํ๋ด๋ผ ์ ์๋ค๋ ์ ์ด๋ค.
// counter์ ํ ๋น๋ ์ด ์ต๋ช
ํจ์๋ ์ ์๋๋ ์ฆ์ ์คํ๋๋ค.
// ์ด lexical environment๋ privateCounter๋ผ๋ ๋ณ์์ changeBy๋ผ๋ ํจ์๋ฅผ ํฌํจํ๋ค.
// 2๊ฐ ๋ค private item์ด๋ค. ์ต๋ช
ํจ์ ์ธ๋ถ์์ ์ ๊ทผ๋ ์ ์๋ ์์ด๋ค์ด๋ค.
// ๋์ ์ต๋ช
ํจ์์์ ๋ฐํ๋ 3๊ฐ์ public ํจ์๋ฅผ ํตํด์๋ง ์ ๊ทผํ ์ ์๋ค.
let counter = (function() {
let privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
// counter.increase, counter.decrease, counter.value ๋ ๊ฐ์ lexical ํ๊ฒฝ์ ๊ณต์ ํ๋ค.
increase: function() {
changeBy(1);
},
decrease: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
};
})();
counter.increase();
counter.increase();
console.log(counter.value()); // logs 2
// ์ต๋ช
ํจ์๋ฅผ ๋ณ๋์ ๋ณ์ makeCounter์ ์ ์ฅํ๊ณ , ์ด ๋ณ์๋ฅผ ์ด์ฉํด ์ฌ๋ฌ๊ฐ์ ์นด์ดํฐ๋ฅผ ๋ง๋ค ์ ์๋ค.
// 2๊ฐ์ counter๋ ๊ฐ์์ ๋
๋ฆฝ์ฑ์ ์งํจ๋ค.
// ํ๋์ ํด๋ก์ ์์ ๋ณ์๊ฐ์ ๋ณ๊ฒฝํด๋ ๋ค๋ฅธ ํด๋ก์ ์ ๊ฐ์๋ ์ํฅ์ ์ฃผ์ง ์๋๋ค.
// -> ์ด๋ฐ ๋ฐฉ์์ผ๋ก ํด๋ก์ ๋ฅผ ์ฌ์ฉํด ๊ฐ์ฒด ์งํฅ ํ๋ก๊ทธ๋๋ฐ์ ์ ๋ณด ์๋๊ณผ ์บก์ํ ๊ฐ์ ์ด์ ์ ์ป์ ์ ์๋ค.
let makeCounter = function() {
let privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
// counter.increase, counter.decrease, counter.value ๋ ๊ฐ์ lexical ํ๊ฒฝ์ ๊ณต์ ํ๋ค.
increase: function() {
changeBy(1);
},
decrease: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
}
};
let counter1 = makeCounter();
let counter2 = makeCounter();
counter1.increase();
counter1.increase();
counter2.decrease();
console.log(counter1.value()); // 2
console.log(counter2.value()); // -1
๐ Closure ์๋ชป๋ ํ์ฉ ๋ฐฉ๋ฒ
๋ฐ์ํ