
전역 변수의 생명주기지역 변수함수의 생명 주기 과정을 살펴보자!function foo() {
var x = 'local';
console.log(x); // local
return x;
}
foo();
console.log(x); // ReferenceError: x is not defined🤔 전역 객체 (참고)
- 클라이언트 사이드 환경 → window
서버 사이드 환경 → global 객체를 의미- 코드가 실행도기 이전 단계에 자바스크립트 엔진에 의해 어떤 객체보다도 먼저 생성되는 특수한 객체
함수 정의와 동시에 호출된다. (단 한 번만 호출됨)
모든 코드를 즉시 실행 함수로 감싸면 모든 변수는 즉시 실행 함수의 ‘지역 변수’가 된다.
(function () {
var foo = 10; // 즉시 실행 함수의 지역 변수
}());
console.log(foo) // ReferenceError: foo is not defined
var MYAPP = {}; // 전역 네임스페이스 객체
MYAPP.name = 'Lee';
console.log(MYAPP.name); // Lee
MYAPP.person = {
name: 'Lee'
address: 'Seoul'
}
console.log(MYAPP.person.name); // Lee
var Counter = (function () {
var num = 0;
return {
increase() {
return ++num;
},
decrease() {
return --num;
},
};
}());
// private 변수는 외부로 노출되지 않는다.
console.log(Counter.num); // undefined
console.log(Counter.increase()); // 1
console.log(Counter.decrease()); // 0