2010-12-10 6 views
0

사람이자바 스크립트

var a = a || 4 // a exists & is 4 
window.a = window.a || 4 // a exists & is 4 
window.a = a || 4 // a is undefined error 
a = a || 4 // a is undefined error 

차이가 이러한 4 개 가지 과제와 이유를 몇 가지가 적절하게 처리하지만, 다른 사람들이하지 않는 사이에 무엇인지에 대한 설명을이 (전역 범위에서 코드)를 설명 할 수 있습니다.

[편집]이 특정 사례는 V8 크롬 콘솔에서 테스트되었습니다.

답변

4
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 
+0

물론. 컴파일 타임에는 정의되지 않지만 런타임에는 선언되지 않는 이유는 무엇입니까? – Raynos

+0

'var' statment는 변수를 가장 가까운 캡슐화 범위에서 선언하고 'undefined'로 설정합니다. 'var'이 없으면 선언 된 변수가 없습니다. 따라서 참조 오류입니다. –

+0

좋은 점은'var bar = 0'이 함수 범위에서 컴파일 타임에 정의되었다는 것을 알지 못했기 때문입니다. 왜 두 개 대신'var' 문 하나만 필요합니까? – Raynos