JS의 클로저

약 1년 전 Flatiron School에 다니면서 Javascript를 배우기 시작했습니다. 일반적으로 JS는 처음에는 Ruby/Ruby on Rails 배경에서 약간 이상했습니다. JS에서 이해하기 가장 어려운 것 중 하나는 클로저였습니다.

폐쇄란 무엇인가



먼저 JS에서 클로저가 무엇인지에 대해 조금 이야기해 봅시다. 다음은 (MDN)( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures )이 클로저를 정의하는 방법입니다.

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.



범위




클로저가 작동하는 방식을 이해하려면 JS의 범위를 잘 이해하고 있는지 확인하는 것이 좋습니다. 이는 어떤 컨텍스트에서 어떤 변수를 사용할 수 있는지 정의합니다. 전역 변수는 코드의 어느 곳에서나 사용할 수 있으며 함수 외부에서 생성되며 일반적으로 코드 시작 부분에서 생성됩니다. 로컬 변수(로컬 범위)는 함수 내에서 생성되며 해당 함수 내에서만 사용할 수 있습니다.

통사론



클로저는 기본적으로 중첩된 함수이며 내부 함수와 외부 함수가 있습니다. 아래 예에서 updateClicks는 외부 함수이고 reportClicks는 내부 함수입니다. 이것이 의미하는 바는 reportClicks가 자체 범위 내에서 정의된 모든 함수뿐만 아니라 updateClicks 외부 함수에 정의된 모든 변수에 액세스할 수 있다는 것입니다. 여기에서 우리는 reportClicks()를 호출하지 않고 단순히 반환하는 것이므로 나중에 액세스할 수 있습니다.

function updateClicks() {
  let clicks = {};
  function reportClicks(item) {
    clicks[item] = clicks[item] + 1 || 1;  
    console.log(item, clicks);
  }
  return reportClicks();

}



클로저 내의 변수



클로저 내에서 정의된 변수는 다른 변수와 마찬가지로 업데이트 및 변경될 수 있습니다. 다른 예를 살펴보겠습니다. 아래 예에서는 충족된 기준에 따라 무엇meal이 반환될지 결정하기 위해 in/else 문을 사용하고 있습니다.

function hungry(meal) {
    function whatsForDinner() { // whatsForDinner() is an inner function, a closure
      if (!meal) { // whatsForDinner() uses argument provided to the parent function 
        console.log('Is it time to eat?');
      } else if (meal === 'Port Chops') {
        console.log('These are my favorite');
      } else {
        console.log(`I'm eating ${meal} for dinner.`);
      }
    }

    function digest() { // digest() is an inner function, a closure
      meal = undefined; // digest() uses argument provided to the parent function 
    }

    return {
      whatsForDinner,
      digest
    };
  }


요약



이것은 중첩 함수 또는 클로저가 JS에서 작동하는 방식에 대한 약간의 설명입니다. 특히 JS에 정통하지 않은 경우 클로저를 파악하기가 까다로울 수 있습니다. 그들과 함께 연습하고 다른 것과 마찬가지로 그들과 함께 작업하고 앱에서 구현할 수 있습니다!

자원



MDN
ECMA-262-3 in detail. Chapter 6. Closures

좋은 웹페이지 즐겨찾기