var a = a || 4 // var a is evaluated at compile time, so a is undefined here
window.a = window.a || 4 // window.a is simply undefined
window.a = a || 4 // no var a, therefore the variable doesn't exist, = reference error
a = a || 4 // again, no var, reference error
var
문 가까운 밀봉 범위 변수/함수를 선언하고 undefined
으로 설정한다. var
이 없을 때 변수/함수가 전혀 선언되지 않았습니다. 따라서 참조 오류입니다.
몇 가지 예입니다.
function
문 :
foo(); // works
function foo() {}
bar(); // TypeError: undefined is not a function
var bar = function(){};
var
문 : 여기에 차이가 객체와 선언되지 않은 객체에 정의되지 않은 속성이다
function test(foo) {
if (foo) {
var bar = 0; // defined at compile time in the scope of function test
} else {
bar = 4; // sets the bar above, not the global bar
}
return bar;
}
console.log(test(false)); // 4
console.log(bar); // ReferenceError
물론. 컴파일 타임에는 정의되지 않지만 런타임에는 선언되지 않는 이유는 무엇입니까? – Raynos
'var' statment는 변수를 가장 가까운 캡슐화 범위에서 선언하고 'undefined'로 설정합니다. 'var'이 없으면 선언 된 변수가 없습니다. 따라서 참조 오류입니다. –
좋은 점은'var bar = 0'이 함수 범위에서 컴파일 타임에 정의되었다는 것을 알지 못했기 때문입니다. 왜 두 개 대신'var' 문 하나만 필요합니까? – Raynos