클로져

Bruce·2021년 8월 18일

프론트엔드 코어

목록 보기
5/31

클로저란?

Closure is when a function is able to access its lexical scope, even when that function is executing outside its lexical scope.
렉시컬 스코프(정적 스코프)로 인해 내부함수에서 외부함수의 스코프에 접근이 가능한것.
클로저는 렉시컬 스코프에 의해 자신이 생성될 때의 환경(Lexical environment)을 기억하는 함수다.

클로저의 활용

  • 상태 유지
  • 전역 변수의 사용 억제
  • 은닉화

예제

function animal(){
    const cat = 'meow';
    const puma = function () {
        console.log(cat);
    }
    return puma;
}

const tiger = animal();

tiger();
// meow

모듈패턴

function close() {
    let item = 0;
    return {
        increment: function() {
            item++;
            console.log(item);
        },
        decrement: function() {
            item--;
            console.log(item);
        }
    }
}

const fulfillment = close();
fulfillment.increment();
// 1
// 0
profile
Figure it out yourself

0개의 댓글