Notice
Recent Posts
Recent Comments
«   2026/01   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

MJ.Story

[Deep dive]클로저 본문

IT/Javascript

[Deep dive]클로저

아토씌 2022. 12. 9. 00:20

클로저

  • 클로저는 둘러싸여진 상태의 참조와 함께 다발로 묶여진 함수의 콤비네이션이다.
  • 바꿔말하면 클로저는 내부 함수로부터 외부함수의 접근권한을 준다.
  • 클로저는 함수 생성 시점에 언제나 생긴다.
// 24-1
const x = 1;
function outerFunc() {
  const x = 10;

  function innerFunc() {
    console.log(x);
  } // <- innerFunc와 outerFunc 사이의 closuer (oER)
  innerFunc();
} // <- outerFunc와 전역컨텍스트 사이의 closuer (oER)
outerFunc();
// 24 - 3
const x = 1;

function foo() {
  const x = 10;
  bar();
}
function bar() {
  console.log(x);
}

foo(); // ?
bar(); // ?
// 24-5
// 1
const x = 1;
function outer() {
    const x = 10;
    const inner = function () { console.log(x); }; // 2
    return inner;
}

// outer 함수를 호출하면 중첩 함수 inner를 반환한다.
// 그리고 outer 함수의 실행 컨택스트는 실행 컨텍스트 스택에서 팝되어 제거된다.
const innerFunc = ounter(); // 3. inner() {...}
innerFunc(); // 4. 10
// 24-9
let num = 0;

const increase = function () {
  return ++num;
};

console.log(increase()); // 1
console.log(increase()); // 2
console.log(increase()); // 3

num = num + 1;
console.log(num);