class Counter {
constructor() {
//여기 컨스트럭쳐안에는 데이터 타입만 즉, 초기값 설정 세팅 부분
this.counter = 0;
}
//여기는 함수 등...
increase() {
this.counter++;
console.log(this.counter);
if (this.counter % 5 === 0) {
//즉 5 10 15 20
console.log("yo");
}
}
}
const coolCounter = new Counter();
coolCounter.increase(); // 1..
coolCounter.increase(); // 2..
coolCounter.increase(); // 3..
coolCounter.increase(); // 4..
coolCounter.increase(); // 5 가 되었으니 yo 가 로그에 출력됨.
///////////////////////////////////////////////////////////////////////////////////////////
//근데 이 방법 말고,
// 콜백함수를 전달하는 방법으로 하면,
increase(콜백함수) {
this.counter++;
console.log(this.counter);
if (this.counter % 5 === 0) {
//즉 5 10 15 20
//console.log("yo");
콜백함수(this.counter);
}
}
function printSomething(num){
console.log('yo' ${num});
}
function alertNum(num){
alert('wow' ${num});
}
const coolCounter = new Counter();
coolCounter.increase(printSomething); // 1..
coolCounter.increase(printSomething); // 2..
coolCounter.increase(printSomething); // 3..
coolCounter.increase(printSomething); // 4..
coolCounter.increase(printSomething); //yo!
coolCounter.increase(printSomething); // 6..
coolCounter.increase(printSomething); // 7..
coolCounter.increase(printSomething); // 8..
coolCounter.increase(printSomething); // 9..
coolCounter.increase(alertNum); //yo!
////////////////////////////////////////////////////////////////////////////
//지금 문제점은
// increase 함수를 호출할떄마다, 콜백함수를 전달하려니 너무 불편함.
// 그래서 increase 함수에는 이제, 콜백함수를 받지않고,
// constructor함수에서 콜백을 받는다.
class Counter {
constructor(콜백함수) {
//여기 컨스트럭쳐안에는 데이터 타입만 즉, 초기값 설정 세팅 부분
this.counter = 0;
this.callback = 콜백함수;
}
increase() {
this.counter++;
console.log(this.counter);
if (this.counter % 5 === 0) {
//즉 5 10 15 20
//console.log("yo");
//콜백함수(this.counter);
if(this.callback){
//콜백이 있을경우 이거를 실행
this.callback(this.counter);
}
//this.callback && this.callback(this.counter); 간략하게 이거써도됨.
}
}
const coolCounter = new Counter(printSomething); // 근데 여기 인자가 만약 비어있으면 undefined니까 에러나니까, increase에서 if 문 해준다.
const coolCounter = new Counter(alertNum);
coolCounter.increase(); // 1..
coolCounter.increase(); // 2..
coolCounter.increase(); // 3..
coolCounter.increase(); // 4..
coolCounter.increase(); //yo!
coolCounter.increase(); // 6..
coolCounter.increase(); // 7..
coolCounter.increase(); // 8..
coolCounter.increase(); // 9..
coolCounter.increase(); //yo!
////////////////
//위에꺼보단
const printCounter = new Counter(printSomething);
const alertCounter = new Counter(alertNum);