analogcoding

Closure 본문

Study JS for me/Keyword

Closure

be well 2019. 4. 23. 19:00

Closure

외부함수의 변수에 접근할 수 있는 내부함수.
scope chain으로 표현되기도 한다.

보통 함수를 return하여 사용하고 return 하는 내부함수를 closure함수라고 칭한다.

 

Closure가 가지는 세가지 scope chain

 

  1. Closure 자신에 대한 접근. (Closure function 내에 정의된 변수)
  2. 외부함수의 변수에 대한 접근
  3. 전역 변수에 대한 접근
function outer(){
  console.log("outer");
  function inner(){
    console.log("inner")
  }
  return inner;
}

outer()   // outer;
outer()() // outer;
          // inner;
var what = outer();
what()    // inner;

Closure 의 외부함수의 변수값은 내부함수에 의해 변경될 수 있다.

function outerChange() {
   var newId = '새로운 아이디';
   
   return {
    getId : function() {
       return newId;
     },
    changeId : function(id) { 
//내부함수가 외부함수의 변수값을 변경하게 함.
       newId = id;
     }
  }
}

var change = outerChange();
change.getId()// '새로운 아이디'
change.changeId('변경된 아이디')
change.getId()// '변경된 아이디' => 변경된 값을 리턴함.

또한 Closure를 이용해 변수를 scope 안 쪽에 숨겨서 함수 밖으로 노출시키지 않을 수도 있다.

function Counter() {
  // 카운트를 유지하기 위한 자유 변수
  var counter = 0;

  // 클로저
  this.increase = function () {
    return ++counter;
  };

  // 클로저
  this.decrease = function () {
    return --counter;
  };
}

const counter = new Counter();

console.log(counter.increase()); // 1
console.log(counter.decrease()); // 0

Scope와 Closure가 늘 짝처럼 붙어다니는 이유를 조금은 알 것 같다. 두 규칙을 이해하지 못한 채 코드를 작성한다면
어느 변수를 어디서 받아오는지에 대해 정확히 알지 못할 것이기 때문에.. 
여러 훌륭한 분들의 글을 보며 간단하게 내가 보기 편하게 정리해보았다.

 

정리가 되지않고 헷깔릴 때마다 내가 찾아올 수 있는 글들을 계속 작성할 예정이다 🤣

'Study JS for me > Keyword' 카테고리의 다른 글

Template literals  (0) 2019.05.11
ES6 : let , const  (0) 2019.05.10
call & apply & bind  (0) 2019.04.27
Execution context 와 This  (0) 2019.04.26
Scope [global , local] / Hoisting  (0) 2019.04.23
Comments