전역 변수의 문제점
-
14장 전역 변수의 문제점 | 모던 자바스크립트 Deep Dive모던 자바스크립트 Deep Dive 2023. 11. 10. 18:55
변수의 생명 주기 지역 변수의 생명 주기 var x = 'global'; function foo() { console.log(x); // undefined var x= 'local'; } foo(); console.log(x); // global 위 예제의 foo 함수를 호출하면 함수 몸체의 다른 문들이 순차적으로 실행되기 이전에 x 변수의 선언문이 자바스크립트 엔진에 의해 가장 먼저 실행되어 x 변수가 선언되고 undefined로 초기화된다. 그 후, 함수 몸체를 구성하는 문들이 순차적으로 실행되기 시작하고 변수 할당문이 실행되면 x 변수에 값이 할당된다. 그리고 함수가 종료되면 x 변수도 소멸되어 생명 주기가 종료된다. 즉, 지역 변수의 생명 주기는 함수의 생명주기와 일치한다. 이처럼 호이스팅은 스코..