Dev
Javascript 전역변수
DT_Tracker
2021. 4. 20. 17:32
반응형
아래 예시를 보면 쉽게 이해가 가능하다.
말 그대로 전 지역에서 접근할 수 있는 변수라 해서 전역변수이다.
var Vscope = 'global';
function Fscope(){
document.write(Vscope);
}
function Fscope2(){
document.write(Vscope);
}
Fscope(); //global 출력
Fscope2(); //global 출력
//애플리케이션 전지역에서 접근할수 있는 변수라 해서 전역변수이다.
//함수 안에다가 지정을 하게되면 함수 안에서만 접근이 가능하다.
var vscope = 'global';
function fscope(){
var vscope = 'local';
var lv = 'local variables';
document.write(lv);
}
fscope(); //loacl varivables가 실행된다.
document.write(lv); //undefined가 나온다.함수 내에서 정의된변수를 함수로써 사용하는게
// 아니라면 사용할 수 없다. 즉 함수내에서 만들어진 lv는 지역변수이다.
var vscope = 'global';
function fscope(){
var vscope = 'local';
}
fscope(); // local
document.write(vscope); //global이 출력된다.
-----------------------------------------------------
var vscope = 'global';
function fscope(){
vscope = 'local'; //var을 빼면
}
fscope();
document.write(vscope); //local 이 출력된다.
//즉 var 빼면 vscope 자체가 local로 재정의?? 되어서 local이 출력된다 라고 생각하자.
// 쉽게 말하면 var을 빼버리면 지역변수말고 전역변수를 사용해버린다.
var vscope = 'global';
function fscope(){
var vscope = 'local';
vscope = 'local';
}
fscope();
document.write(vscope);
//위에서도 var을 사용할때까진 local이 실행되는데 그밑에 var을 빼고 한번 더 실행이
// 되어서 또 다시 지역변수가 아닌 전역변수를 사용하게 된다. 지역변수를 쓰려고한다면
// 반드시 var을 붙혀서 사용해야한다.
반응형