글로벌 스코프
스크립트 전체에서 변수가 유효하다.
로컬 스코프
정의된 함수 안에서만 변수가 유효하다.
var로 선언된 변수는 로컬 스코프에 해당한다.
if (true) {
var name = 'Park';
}
console.log(name); // Park
var로 선언된 변수는 블록 스코프가 아니므로 블록을 빠져나온 후에도 변수가 유효하여 게속 사용할 수 있다.
var a = 0;
(function() {
a++;
console.log(a); // 1
})();
console.log(a); // 1
(function() {
var b = 0;
console.log(b); // 0
})();
b++;
console.log(b); // Error
a는 전역에 선언되었으므로 스크립트 전체에서 유효하지만 b는 익명 함수 내에서만 유효하므로 전역에서 호출된 콘솔문은 유효하지 않다.
글로벌 변수와 로컬 변수
var scope = 'A';
function getValue() {
var scope = 'B';
return scope;
}
console.log(getValue()); // B
console.log(scope); // A
scope = 'A';
function getValue() {
scope = 'B';
return scope;
}
console.log(getValue()); // B
console.log(scope); // B
위 두 예제를 통해서 var 를 사용하지 않고 선언된 변수는 모두 글로벌 변수로 간주되는 것을 알 수 있다.
로컬 변수를 정의하려면 반드시 var로 선언해야 한다.
로컬 변수의 유효 범위
var scope = 'A';
function getValue() {
console.log(scope); // 'undefined'
var scope = 'B';
return scope;
}
console.log(getValue()); // B
console.log(scope); // A
함수 getValue가 초기 호출될 때 콘솔문에서 변수 scope는 유효하다.
이는 호이스팅에 의해 변수 scope의 선언문만 함수의 선두에 위치하도록 되어있기 때문이다.
즉 함수 getValue는 다음과 같게 된다.
function getValue() {
var scope;
console.log(scope); // 'undefined'
scope = 'B';
return scope;
}
이러한 동작은 프로그램 버그의 원인이 되기도 하므로 로컬 변수는 함수의 선두에 직접 선언하도록 하자.
블록 스코프
블록 안에서만 변수가 유효하다.
let, const로 선언된 변수는 블록 스코프에 해당한다.
if (true) {
let name = 'Park';
}
console.log(name); // Error
let, const로 선언된 변수는 해당 블록에서만 유효하므로 블록을 빠져나오면 유효하지 않다.
let score = 90;
'프론트엔드 > JavaScript' 카테고리의 다른 글
[이슈 처리] Blocked a frame with origin "https://xxx" from accessing a cross-origin frame (0) | 2024.01.26 |
---|