class Counter {
constructor() {
this.counter = 0; //Counter라는 클래스를 이용해 오브젝트가 만들어지는 순간 counter = 0으로 초기화
}
increase() { //class에는 함수 만들 때, function 안써도 됨
this.counter++;
console.log(this.counter);
}
}
//class 생성
const coolCounter = new Counter();
class Counter {
constructor() {
this.counter = 0;
}
increase() {
this.counter++;
console.log(this.counter);
//counter가 5의 배수일 때 알려주는 함수
if(this.counter %5 ===0){
runIf5Times(this.counter);
}
}
}
//class 생성
const coolCounter = new Counter();
//더 쉽게 바꿀 수 있도록 함수 설치
function printSomething(num){
console.log(`yo! ${num}`);
}
coolCounter.increase(printSomething); //1
coolCounter.increase(printSomething); //2
coolCounter.increase(printSomething); //3
coolCounter.increase(printSomething); //4
coolCounter.increase(printSomething); //yo! 5
coolCounter.increase(printSomething); //6
coolCounter.increase(printSomething); //7
coolCounter.increase(printSomething); //8
coolCounter.increase(printSomething); //9
coolCounter.increase(printSomething); //yo! 10
→ 위의 코드로 하면 increase를 계속 호출해야할 때마다 계속 전달해야해서 힘듦
⇒ counstructor에 콜백함수 받음 (아래 코드 참조)
class Counter {
constructor(runEveryFiveTimes) {
this.counter = 0;
this.callback = runEveryFiveTimes; //callback 변수에 할당
}
increase() {
this.counter++;
console.log(this.counter);
//counter가 5의 배수일 때 알려주는 함수
if(this.counter %5 ===0){
this.callback(this.counter);
}
}
}
function printSomething(num){
console.log(`yo! ${num}`);
}
const coolCounter = new Counter(printSomething);
coolCounter.increase(); //1
coolCounter.increase(); //2
coolCounter.increase(); //3
coolCounter.increase(); //4
coolCounter.increase(); //yo! 5
coolCounter.increase(); //6
coolCounter.increase(); //7
coolCounter.increase(); //8
coolCounter.increase(); //9
coolCounter.increase(); //yo! 10
class Counter {
constructor(runEveryFiveTimes) {
this.counter = 0;
this.callback = runEveryFiveTimes; //callback 변수에 할당
}
increase() {
this.counter++;
console.log(this.counter);
//counter가 5의 배수일 때 알려주는 함수
if(this.counter %5 ===0){
if(this.callbacok){ //callback함수가 인자로 전달 받았을 때만 호출
this.callback(this.counter);
}
// 위의 코드 간단 버전 : this.callback && this.callback(this.counter);
}
}
}
function printSomething(num){
console.log(`yo! ${num}`);
}
const coolCounter = new Counter(); // callback함수 전달x
coolCounter.increase(); //1
coolCounter.increase(); //2
coolCounter.increase(); //3
coolCounter.increase(); //4
coolCounter.increase(); //yo! 5
coolCounter.increase(); //6
coolCounter.increase(); //7
coolCounter.increase(); //8
coolCounter.increase(); //9
coolCounter.increase(); //yo! 10
이렇게 하면 좋은점
// 위의 코드와 동일
function printSomething(num){
console.log(`wow! ${num}`);
}
function alertNum(num){
alert(`Alert! ${num}`);
}
const printCounter = new Counter(printSomething);
const alertCounter = new Counter(alertNum);