class Counter {
constructor(runEveryFiveTimes) { //2) 메서드 대신 콜백 함수를 생성자에 집어넣으면 더 간단하다.
this.counter = 0;
this.callback = runEveryFiveTimes;
}
increase() {
this.counter++;
console.log(this.counter);
if (this.counter % 5 === 0) {
this.callback && this.callback(this.counter);
}
}
}
function printSomething(num) {
console.log(`Wow! ${num}`);
}
function alertNum(num) {
alert(`wow! ${num}`);
};
const printCounter = new Counter(printSomething);
const alertCounter = new Counter(alertNum);
//1) 클래스의 메서드에 콜백함수를 넣음으로써
// 사용자가 원하는 기능을 클래스 밖에서 customize할 수 있다.
// coolCounter.increase(alertNum);
for (let i=0; i<5; i++) {
printCounter.increase();
}
for (let i=0; i<5; i++) {
alertCounter.increase();
}
// 클래스는 하나의 완벽한 틀보다는 계속해서 조립하는 레고라고 생각하자.
// 이것저것 만들어보자.
'개발 공부 > 자바스크립트' 카테고리의 다른 글
[엘리의 드림코딩 JS] ES6 - ES11 핵심 문법들 (0) | 2022.12.07 |
---|---|
[엘리의 드림코딩 JS] 직접 쇼핑몰 사이트 HTML, CSS, JS로 만들기 (0) | 2022.12.07 |
[엘리의 드림코딩 JS 보충] 17. Boolean의 모든 것, &&연산자 (0) | 2022.12.06 |
[엘리의 드림코딩 JS 보충] 16. 함수 정의, 호출, 그리고 콜백 함수 (0) | 2022.12.06 |
[엘리의 드림코딩 JS 보충] 15. 변수(primitive vs object) (0) | 2022.12.06 |