자바스크립트의 클로저

Mar 18 2023
클로저는 무엇이며 언제 사용할 수 있습니까? Closure를 이해하려면 JavaScript의 두 가지 간단한 개념인 중첩 함수와 함수 반환에 대해 알아야 합니다. 중첩 함수 JavaScript에서는 중첩 함수를 가질 수 있습니다.

클로저는 무엇이며 언제 사용할 수 있습니까?

Closure를 이해하려면 JavaScript의 두 가지 간단한 개념인 중첩 함수와 함수 반환에 대해 알아야 합니다.

중첩 함수

JavaScript에서는 중첩 함수를 가질 수 있습니다. 내부 함수는 외부 함수의 변수 및 매개변수에 액세스할 수 있습니다.

다음 예를 확인해 보겠습니다.

function greetPerson(name) {
  const message = 'Hello';
  
  function displayMessage() {
    console.log(`${message} ${name}!`);
  }

  displayMessage();
}

greetPerson('Alex'); // Hello Alex!

함수 반환

외부 함수 내에서 내부 함수를 선언하고 호출하는 것 외에도 외부에서 호출할 수 있도록 내부 함수를 반환할 수도 있습니다.

이에 대한 예를 살펴보겠습니다.

function greetPerson(name) {
  const message = 'Hello';
  
  function displayMessage() {
    console.log(`${message} ${name}!`);
  }

  return displayMessage;
}

const displayMessageFunction = greetPerson('Alex');

console.log(typeof(displayMessageFunction)); // function
displayMessageFunction(); // Hello Alex!

폐쇄

이 두 가지 개념을 이해하고 나면 클로저의 "정의"는 매우 간단합니다.

클로저는 외부 함수가 반환된 후에도 내부 함수가 외부 함수의 변수 및 매개변수에 액세스할 수 있음을 의미합니다.

클로저가 어떻게 사용될 수 있는지 정확히 볼 수 있는 또 다른 예를 살펴보겠습니다.

function counterFunction() {
 let counter = 0;

 function increaseCounter() {
  return counter += 1;
 }

 return increaseCounter;
}

// counter reffers to the increaseCounter returned by the counterFunction
const counter = counterFunction();

console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
console.log(counter()); // 4

내부 함수는 외부 변수의 별도 복사본을 유지하지 않지만 외부 변수를 참조합니다. 즉, counter내부 함수를 사용하여 변경하면 the의 값이 변경됩니다.

외부 함수는 내부 함수 counterFunction에 대한 참조도 반환하므로 increaseCounter호출하면 변수의 실제 값이 counter변경됩니다. 이런 식으로 우리는 counter변수가 모든 호출 후에 새로운 증분 값을 갖는 것을 볼 수 있습니다 counter().

클로저를 언제 사용합니까?

클로저를 사용하여 JavaScript에서 캡슐화를 달성할 수 있습니다. 이는 세부 구현을 숨겨서 수행할 수 있습니다. 이런 식으로 개인 변수와 함수를 만들 수 있습니다.

함수와 객체만 사용하여 일부 데이터를 캡슐화하려는 다음 예제를 확인해 보겠습니다.

const counter = (function () {
  let privateCounter = 0;

  function changeBy(val) {
    privateCounter += val;
  }

  function increaseCounter() {
    changeBy(1);
  }

  function decreaseCounter() {
    changeBy(-1);
  }

  function decreaseCounter() {
    return privateCounter;
  }

  return { increaseCounter, decreaseCounter, getCounterValue };
})();

console.log(counter.getCounterValue()); // 0

counter.increaseCounter();
counter.increaseCounter();

console.log(counter.getCounterValue()); // 2

counter.decreaseCounter();

console.log(counter.getCounterValue()); // 1

카운터의 값은 외부에서 increaseCounter와 를 호출해야만 제어할 수 있으며 getter처럼 동작하는 함수를 decreaseCounter호출하여 값을 가져올 수 있습니다 .getCounterValue

public이러한 방식으로 및 액세스 지정자를 시뮬레이션하고 캡슐화를 달성할 수 있습니다 private.

이는 비공개로 유지되어야 하는 변수 및 함수에 대한 의도하지 않은 수정을 방지하므로 소프트웨어 개발에서 매우 강력한 개념입니다.

그게 다야!

시간을 내어 JavaScript 클로저에 대한 이 글을 읽어주셔서 감사합니다. 이 중요한 개념과 캡슐화를 달성하고 개인 변수 및 함수를 만드는 데 어떻게 사용할 수 있는지 더 잘 이해하는 데 도움이 되었기를 바랍니다.