var counter = (function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
};
})();
console.log(counter.value()); // logs 0
counter.increment();
counter.increment();
console.log(counter.value()); // logs 2
counter.decrement();
console.log(counter.value()); // logs 1class MakeCounter {
private counter: number = 0;
public changeBy(val: number): void {
this.counter += val;
}
public increment() {
this.changeBy(1);
}
public decrement() {
this.changeBy(-1);
}
public value() {
return this.counter;
}
}Private method ๋ ๊ทธ๋ฅ class ์ฐ๋ฉด ๋๋๋ฐ ๊ตณ์ด ์ฌ์ฉํ๋ ์ด์ ๋ ๋ญ๊น?
์๋ฌธ์๋ต: ํด๋ก์ ๋ ์ค์ฝํ ๋ฌธ์ ๋ก ์ฌ์ฉํ๋ ๊ฒฝ์ฐ๊ฐ ์์. ํด๋ก์ ๋ฅผ ์ฌ์ฉํ์ง ์์ผ๋ฉด ์๋ฐ์คํฌ๋ฆฝํธ ๋ณ์๊ฐ var๋ก ์ ์ธ๋๊ฑฐ๋ function์ด ํ์ผ ์ ์ฒด์์ ์ค๋ณต๋๋ ๋ฌธ์ ๊ฐ ์๊ฒจ์ ์ด๋ฅผ ๋ฐฉ์งํ๊ธฐ ์ํด์ ํด๋ก์ ๋ฅผ ์ฌ์ฉํจ.
์ฐธ๊ณ