본문 바로가기
JAVA/javascript, jQuery

자바스크립트 - 전역변수/지역변수

by 설총이 2018. 7. 3.

전역변수 예제.


*전역 변수 :: 어떠한 변수 영역에서도 접근할 수 있는 변수를 의미


자바스크립트에서는 type을 안적어도 되고,

var도 안적어도 변수선언이 가능하다

그러나 자바와 똑같은 기능인

메서드 내에서 지역변수가 우선권을 가지는것처럼

function내에서도 지역변수가 우선권을 가지는데,


★★var선언 없이 그냥 변수로 선언하면 그 변수는 전역변수가되어

메서드내에서만 쓸 수 있는 지역변수가 아니게된다.



1
2
3
4
5
6
7
8
9
10
11
12
13
<script>
    /*var없이 변수 선언시 전역변수가 된다.*/    
        var scope = "global";
            function checkscope(){
            scope="local";
            document.write(scope);
            myscope="mylocal";;
            document.write(myscope);
        }
        checkscope();
        document.write(scope);
        document.write(myscope);
</script>
cs


checkscope() 안에 있는 scope = "local";의 값은

외부에 선언된 var scope = "global";과 같은 변수로 인식해서

기존에 global로 저장되어있던 scope의 값은 local로 바뀌어 저장하게 된다.


그래서 밖에서 호출하는 document.write(scope)는 global이 아닌 local이 되고

document.write(myscope) 또한,

메서드처럼 원래는 function이 쓰이고 안의 정보가 소멸된채로 호출되기때문에

myscope is not defined 가 콘솔창에 출력되게 되어야 하지만


전역변수로 저장되어서 mylocal이 출력되게 되는것이다.


----------------------------------------------------------------------------------------



*function 내에서의 function 선언과 지역변수 예제



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>
   var scope = "global";
       function checkscope(){
         var scope = "local";
           function nested(){
            var scope = "nest";
            document.write(scope);
           }
           document.write(scope);
// local 출력. 근접한 지역변수호출 
          nested(); // nest 호출
      } // 펑션이 끝나면서 메서드처럼 소멸된다.
      checkscope();
      nested(); // 소멸되었기때문에 호출할수가없어서 is not defined가 뜬다.
      
      document.write(scope);
</script>

cs


마지막 document.write(scope)는 처음 선언한 global이 떠야하지만,

위에 nested(); 에서 에러가나서 그 뒤의 문장을 실행하지 않는다.

그래서 이 호출은 취소가된다.



--------------------------------------------------------------------------------------------------------



function 내에 변수가 선언되어있는 상태라면,

변수 선언하기전에 호출을 하여도 값이 저장안되어있을뿐

var scope; 가 선언 되어 있다.


1
2
3
4
5
6
7
8
9
10
11
12
<script>
    var scope = "global";
        function f(){
    /*var scope; 생략된 상태.
함수안에 변수가 선언된 경우에, 
    어디든 상관없이 끌어 올려 제일 첫 줄에 선언 되어있다.*/
            alert(scope); //undefined 출력
            var scope="local";
            alert(scope); //local 출력
        }
        f();
        
</script>
cs



그렇기때문에 이 예제에서 f(); 로 메서드를 호출할때,

처음 alert(scope)는 값이 없는 undefined가 뜬다