Skip to content

Latest commit

ย 

History

History
64 lines (50 loc) ยท 1.41 KB

File metadata and controls

64 lines (50 loc) ยท 1.41 KB

ํด๋กœ์ €๋ฅผ ์ด์šฉํ•ด์„œ ํ”„๋ผ์ด๋น— ๋ฉ”์†Œ๋“œ (private method) ํ‰๋‚ด๋‚ด๊ธฐ

MDN

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 1

๋‚ด ์˜๊ฒฌ

class 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์ด ํŒŒ์ผ ์ „์ฒด์—์„œ ์ค‘๋ณต๋˜๋Š” ๋ฌธ์ œ๊ฐ€ ์ƒ๊ฒจ์„œ ์ด๋ฅผ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•ด์„œ ํด๋กœ์ €๋ฅผ ์‚ฌ์šฉํ•จ.

์ฐธ๊ณ