Web

[Javascript] 클로저 예시

오즈마스터 2022. 7. 13. 09:28

클로저를 사용한 Counting

0

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>        
        <script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
    </head>
    <body>
        
        <p>클로저를 사용한 Counting</p>
        <button id="increase">+</button>
        <p id="count">0</p>

        <script>                    
            function counterFunc()
            {
                let counter = 0;
                
                return function(){
                    
                    counter++;
                    return counter;
                };
            }
            
            countfunc = counterFunc();
            $('#increase').on('click', function() {
                let counter = countfunc();                
                $('#count').text(counter);
            });            
        </script>
    </body>
</html>