1 분 소요


<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>클로저 함수-1</title>
    <script>
        //일반함수에서의 지역변수는 함수가 종료가 되면 같이 메모리에서 제거가
        //되는게 일반적이다.
        // function add(){
        //     var cnt = 0;
        //     cnt++;
        //     return cnt;
        // }
        // document.write("1번째 cnt 값 : " + add() + "<br/>");
        // document.write("2번째 cnt  : " + add() + "<br/>");
        // document.write("3번째 cnt  : " + add() + "<br/>");
        // document.write("4번째 cnt  : " + add() + "<br/>");
        // document.write("5번째 cnt  : " + add() + "<br/>");
        //클로저 이용
        function createCounter() {
            var cnt = 0;  //지역변수를 선언했다.
            //add()는 클로저 함수가 된다.
            function add(){
                //외부함수의 지역변수를 이용하고 있다.메모리에서 제거가 안된다.(클로저 현상)
                cnt++;   
                return cnt;
            }
            return add;
        }
        var counter = createCounter(); //함수리터럴
        document.write("1번째 cnt  : " + counter() + "<br/>");
        document.write("2번째 cnt  : " + counter() + "<br/>");
        document.write("3번째 cnt  : " + counter() + "<br/>");
        document.write("4번째 cnt  : " + counter() + "<br/>");
        document.write("5번째 cnt  : " + counter() + "<br/>");
    </script>
</head>
<body>
    
</body>
</html>

image


<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>클로저 함수-2</title>
    <script src="libs/jquery-3.5.1.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btnStart").click(function(){
                start();
                document.write("시작합니다.");
            });
            //2초마다 cnt를 출력하게 된다.
            function start(){
                var cnt = 0;
                //클로저 함수
                setInterval(function(){
                    cnt++;   //외부함수의 지역변수를 사용(메모리에서 제거가 않됨)
                    document.write(cnt);
                }, 2000);
            }
        });
    </script>
</head>
<body>
    <button id="btnStart">시작</button>
</body>
</html>

댓글남기기