본문 바로가기

자바스크립트

[인간 JS엔진 되기] 1-4,5. 스코프 체인 및 호이스팅

스코프 체인

스코프를 통해서 어떤 함수에서 어떤 변수를 접근 할 수 있음

 

const 변수는 블록 스코프를 가짐

 

 

const x = 'x'; //없애면 c에서 x를 출력하면 reference error 발생
function c() {
    const y= 'y';
    console.log('c   ', x)
}

function a() {
    const x = 'xxx'
    console.log('a   ', x)
    function b() {
        const z = 'z';
        console.log('b   ', x);
        c();
    }
    b();
}

a();
c();

 

함수 a,c는 전역 스코프

b는 c의 호출 스택 스코프

 

왼쪽 : anonymous 스코프 / 오른쪽 : a의 스코프

 

 

호이스팅

호이스팅가 발생할 상황 자체를 안만들어야함

아래는 a() 호출 시, b가 undefined된 스코프를 a 메소드가 가지고 있어 ReferenceError가 발생

이런 호이스팅을 방지해야 좋은 코드!

const x = 'x'; //없애면 c에서 x를 출력하면 reference error 발생
function c() {
    const y= 'y';
    console.log('c   ', x)
    function b() {
        const z = 'z';
        console.log('b   ', x);
        c();
    }
}

function a() {
    const x = 'xxx'
    console.log('a   ', x)

    b();
    console.log(x);
}

a();
c();