클로저(Closure)

수연·2023년 4월 6일
0
post-thumbnail

클로저(Closure)

  • 자신이 생성될 때의 환경(Lexical environment)를 기억하는 함수

Lexical environment

  • 내부 함수가 선언되었을 때의 스코프

클로저 예시

const order = (food) => {
  console.log(`${food}(을)를 주문하셨습니다.`)
  return function(drink) {
    return `${drink}(을)를 추가로 주문하셨습니다.`
  }
}

const orderChicken = order('치킨');
const orderBugger = order('햄버거');
console.log(orderChicken('맥주'))
console.log(orderBugger('제로콜라'));

위와 같은 코드가 있다면 아래와 같이 진행이 된다.
1. order('치킨') 실행
2. '치킨'을 주문하셨습니다. 출력
3. orderChicken에 function(drink) 함수 저장
4. order('햄버거') 실행
5. '햄버거'를 주문하셨습니다. 출력
6. orderBugger에 function(drink) 함수 저장
7. orderChicken('맥주') 실행
8. '맥주'를 추가로 주문하셨습니다. 출력
9. orderBugger('제로콜라') 실행
10. '제로콜라'를 추가로 주문하셨습니다. 출력

클로저 필요성

1. 전역 변수 줄임

- 전역 변수의 수가 많으면, 코드 어디서나 접근 가능으로인한 위험성 증가
<br/>
**전역 변수 사용**
let count = 0;
function onClickButton() {
  count++
  return count;
}

클로저 사용

function onClickButton() {
  let count = 0;
  return function(){
    count++;
    return count;
  }
}

2. 비슷한 코드 재사용

const newTag = function(open, close) {
  return function(content) {
      return `${open}${content}${close}`
  }
}
const bold = newTag('<b>', '</b>');
const italic = newTag('<i>', '</i>');
console.log(bold(italic("내용입니다."))); // <b><i>내용입니다.</i></b>

착각하기 쉬운 클로저

function introduce() {
  let name = 'sally';
  if (true) {
    let city = 'seoul';
    return function location() {
      console.log(city);
    };
  }
}

위의 코드는 내부에서 선언된 함수가 외부함수의 지역 변수를 사용하지 않아 클로저가 아니다.

클로저로 사용하기 위해선 아래와 같이 name을 사용하도록 변경하여 사용한다.

function introduce() {
  let name = 'sally';
  if (true) {
    let city = 'seoul';
    return function location() {
      console.log(city);
      console.log(name);
    };
  }

0개의 댓글