본문 바로가기
JS/Concept

Closure

by kiberd 2021. 12. 27.

Closure makes it possible for a function to have ‘private’ variables.

function outer(){
  const name = 'kyle';
  console.log(name)
  return function inner(){
    const greeting = 'hello!'
    console.log(greeting,name)
  }
}
const getKyle = outer() //kyle 
getKyle() //hello!kyle

이미 outer가 리턴이 됐음에도 getKyle()을 호출 했을때 outer 의 지역변수인 name에 접근 할 수 있다. 

이런 관계에서 inner와 outer가 클로저 관계에 있다라고 할 수 있다. 

이러한 클로저의 특성을 이용해서 다양한 유연한 프로그래밍을 할 수 있다. 

'JS > Concept' 카테고리의 다른 글

비동기 처리 in JS (Feat. React suspense)  (0) 2022.05.24
this, call, apply, bind  (0) 2021.12.27