개발공부/Sola-Scriptura

함수의 객체(메소드)반환

킴승 2024. 2. 29. 11:57
// 인증번호 카운트다운
function countDown(timerDisplay) {
     // 인증번호 타이머
     let remainingTime = 5 * 60; // 초 단위로 설정 (5분 = 300초)
   
     let timerInterval; // 타이머 ID를 저장할 변수

     function updateTimer() {
     const minutes = Math.floor(remainingTime / 60);
     const seconds = remainingTime % 60;

     const formattedMinutes = String(minutes).padStart(2, '0');
     const formattedSeconds = String(seconds).padStart(2, '0');

     timerDisplay.textContent = `${formattedMinutes}:${formattedSeconds}`;

     if (remainingTime === 0) {
         clearInterval(timerInterval);
         console.log('타이머 종료');
         timerDisplay.style.display = 'none'
     } else {
        // timerDisplay.style.display = 'show'
         remainingTime--;
     }
     }
     
     function manageTimer(action) {
         if (action === 'start') {
             // 타이머 시작
             timerInterval = setInterval(updateTimer, 1000);
         } else if (action === 'stop') {
             // 타이머 종료
             clearInterval(timerInterval);
             console.log('타이머 수동 종료');
         } else if (action === 'reset') {
             // 타이머 초기화
             if(timerInterval){
                 remainingTime = 5 * 60;
             } else {
                 timerInterval = setInterval(updateTimer, 1000);
             }
         }
         }
     // 타이머 시작
     manageTimer('start');

     // 외부에서 타이머를 제어할 수 있도록 반환
    return {  
        stop: () => manageTimer('stop'),
        reset: () => manageTimer('reset')
    };
}

 

아이디 찾기 인증번호 시스템을 만드는 중에 chat gpt의 도움을 받았다. 

인증번호 카운트다운 함수인데, return문이 이해가 되지 않았다.

return으로 객체를 반환하는 것은 보지도 못했고 작성해본 적이 없었기 때문이다.

처음 봤을 때는 객체라는 인식도 하지 못하고, 코드에 콜론을 사용할 수가 있나? 뭐지 이런 생각을 했다...

 
return {  
        stop: () => manageTimer('stop'),
        reset: () => manageTimer('reset')
    };
 

 

gpt를 통해 이 부분에 대해 알아보니 return 뒤의 중괄호는 객체리터럴의 중괄호를 의미했다.

객체를 반환하는 것인가? 하고 생각을 했는데 gpt를 통한 정확한 표현은 

 

return 구문은 객체를 반환하는 것이 아니라, 객체 리터럴을 사용하여 두 개의 함수를 가진 객체를 만들고, 그 객체를 반환하는 것입니다.

 

이다. 단순한 반환이 아닌, 생성과 반환이다. 

 

countDown()함수는 객체 stop, reset을 반환하므로, 아래와 같이 사용할 수 있다.

 

let timeController = countDown(someTimerDisplay)

// 반환된 객체의 stop() 메소드 호출
timeController.stop()

// 반환된 객체의 reset() 메소드 호출
timeController.reset()