class Counter {
  constructor(runEveryFiveTImes) {
    this.counter = 0;
    this.callback = runEveryFiveTImes;
  }

  increase() {
    this.counter++;
    console.log(this.counter);
    if (this.counter % 5 === 0) {
      this.callback(this.counter);
    }
  }
}

const hotCounter = new Counter();

hotCounter.increase();
hotCounter.increase();
hotCounter.increase();
hotCounter.increase();
hotCounter.increase();

✏counter가 5가 됐을때 callback함수가 실행되는데 그때

Counter라는 class를 생성할때 constructor의 인자로 전달해준 callback함수가 없기때문에 this.callback은 undefined가 된다.

Untitled

✔ callback함수가 인자로 있을때만 실행하는 IF문을 넣어주면 에러는 해결된다.

increase() {
    this.counter++;
    console.log(this.counter);
    if (this.counter % 5 === 0) {
      <u>**if (this.callback)</u> {
<u></u>**        this.callback(this.counter);
      }
    }
  }

callback함수가 있다면..

💥 IF문의 간단화

increase() {
    this.counter++;
    console.log(this.counter);
    if (this.counter % 5 === 0) {
	    this.callback && this.callback(this.counter);
    }
  }