[JavaScript] Closures

Sang Young Ha·2021년 12월 29일
post-thumbnail

Closure

  • Douglas Crockford 가 정의한 definition of Closure:
    "Closure means that an inner function always has access to the variables and parameters of its outer function, even after the outer function has returned."
function OuterFunction() {
	var outerVariable = 100;
    
    function InnerFunction() {
    	alert(outerVariable);
    }
    
    return InnerFuction;
}

var innerFunc = OuterFunction();

innerFunc(); // returns 100
  • 위의 예시 코드에서 return InnerFunction 은 OuterFunction() 을 콜 했을때 OuterFunction 에서 부터 InnerFunction을 리턴한다.

  • 변수 innerFunc 는 InnerFunction() 만을 참조(reference) 하며 OuterFunction() 은 참조 하지 않는다.

  • 이러한 이유로, innerFunc() 를 콜 하면, OuterFunction() 내에 선언된 outerVariable 을 access 할 수 있는데, 이를 closure 라 한다.

  • 내부의 함수가 외부 함수의 변수들을 엑세스 할때만이 closure 라고 불린다.

0개의 댓글