2017-10-17 2 views
0

변수가 현재 범위에서 발견되지 않으면 JS 엔진은 전역 스코프에 도달 할 때까지 상위 점수를 찾습니다.window.someRandomVar와 someRandomVar의 차이점

이제, 브라우저에서 나는

console.log(someRandomVariable); 
// This throws ReferenceError as someRandomVariable is Not found on Global/Window scope. 

아래하려고하면하지만 윈도우 객체에 명시 적으로 호출 할 때, 그것은 정의되지 않은 보여줍니다.

console.log(window.someRandomVariable) 

내 이해에 따르면 전자는 특정 기능 범위 안에 있지 않기 때문에 창 개체도 검색합니다.

2 가지 동작이 다른 이유는 무엇입니까?

답변

1
console.log(someRandomVariable); 

자바 스크립트는 범위를 찾을 수 있으며, someRandomVariable을보고 당신이보고있는 예외가 발생합니다. 창 범위가 검색되었다고 말하는 것이 맞지만 창 (또는 범위)에이 변수가 정의되어 있지 않습니다. 그래서 실패합니다.

console.log(window.someRandomVariable) 

자바 스크립트는 window 변수를 검색합니다. 성공하면 someRandomVariable 속성으로 이동합니다. 이것은 정의되어 있지 않으므로 undefined이됩니다.

정의되지 않은 변수의 속성에 액세스하려고 시도하면 오류가 발생할 수 있습니다. 즉, window.someRandomVariable.someRandomVariable을 시도하십시오.


차이점은 하나는 변수 조회이고 다른 하나는 속성 액세스입니다.