[JS] scope

형이·2023년 8월 7일
0

JavaScript

목록 보기
7/20
post-thumbnail

📝 JavaScript

🖥️ 1. 변수의 스코프

<body>
    <script>
        var vscope = 'global';
        function fscope(){
            alert(vscope);
        }

        function fscope2(){
            alert(vscope);
        }

        fscope();
        fscope2();
    </script>
</body>

☑️ 결과 : 'global'이라는 alert창이 두 번 뜸


<body>
    <script>
        var vscope = 'global';
        function fscope(){
            var lv = 'local value';
            alert(lv);
        }
		
        fscope();
        
        // lv 변수의 유효성 범위를 벗어남
        alert(lv);

    </script>
</body>

<body>
    <script>
        var vscope = 'global';
        function fscope(){
            var vscope = 'local';
            alert(vscope);
        }
        fscope();
        alert(vscope);
    </script>
</body>

☑️ 결과 : 'local', 'global'이라는 alert창


<body>
    <script>
        var vscope = 'global';
        function fscope(){
            vscope = 'local';
            alert(vscope);
        }
        fscope();
        alert(vscope);
    </script>
</body>

☑️ 결과 : 변수에 재할당 되었기 때문에 'local'이라는 alert창이 두 번 뜸

0개의 댓글