반응형
다음으로 선언된 변수
var
함수에서 선언된 위치에 관계없이 함수의 맨 위에 "떠다니고" 선언되기 전에도 사용할 수 있는 특별한 속성이 있습니다. 특히 새로운 코더에게는 범위 지정이 혼란스럽습니다.
혼란을 최소화하기 위해,
var
선언은 처음 사용되기 전에 이루어져야 합니다.
나쁜 예:
var x = 1;
function fun(){
alert(x); // Noncompliant as x is declared later in the same scope
if(something) {
var x = 42; // Declaration in function scope (not block scope!) shadows global variable
}
}
fun(); // Unexpectedly alerts "undefined" instead of "1"
좋은 예:
var x = 1;
function fun() {
print(x);
if (something) {
x = 42;
}
}
fun(); // Print "1"
반응형