웹 개발 (Frontend Developer)/JavaScript

JavaScript에서 클로저 (Closure) 이란?

Jackykim 2024. 9. 23. 14:59

<클로저는 뭔가?>

클로저는 함수와 그 주변 상태(렉시컬 환경)에 대한 참조가 함께 묶인 조합입니다. 클로저를 생성하면 내부 함수에서 외부 함수의 스코프에 접근할 수 있습니다.

 

<렉시컬 스코핑은 뭔가?>

렉시컬 스코핑은 (lexical scope) 함수가 중첩될 때 파서가 변수 이름을 어떻게 해결하는지를 의미합니다. 소스 코드 내에서 변수가 선언된 위치가 그 변수가 사용할 수 있는 범위를 결정합니다. 중첩된 함수는 외부 스코프에서 선언된 변수에 접근할 수 있습니다.

렉시컬 스코프 예시

 

<클로저 생산하기>

클로저는 내부 함수가 외부 함수가 실행을 마친 후에도 외부 함수의 변수와 매개변수에 접근할 수 있을 때 형성됩니다. 이는 내부 함수가 자신이 생성된 렉시컬 환경에 대한 참조를 유지하기 때문에 가능합니다.

 

<클로저를 사용해야 할 때>

숫자를 세는 카운터 함수를 작성해 보겠습니다

카운터 함수 예시

 

상단에서 add() 함수를 3번 불렀지만 output (결과)는 1입니다. 함수를 부루 때마다 로컬 카운터가 초기화되어 output이 3이 아닌 1이 됩니다. 이 문제 해결하기 위해 저희는 클로저를 사용하는 것입니다. 

클로저 예시

 

<클로저 사용하는 사레>

- 상태 유지 : 클로저는 이벤트 기반 자바스크립트에서 이벤트 간 상태를 유지하는 데 도움을 줍니다

- 프라이빗 변수 : 클로저를 사용하여 내부에 변수를 감싸서 프라이빗 변수를 만들 수 있습니다

- 콜백 및 비동기 코드 : 클로저는 콜백 처리 및 비동기 작업을 다르는 데 필수적입니다

 

참고 자료 :

https://www.geeksforgeeks.org/closure-in-javascript/

 

Closure in JavaScript - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#lexical_scoping

 

Closures - JavaScript | MDN

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives a function access to its outer scope. In JavaScript, closures are created every time

developer.mozilla.org

https://blog.hubspot.com/website/javascript-closure

 

JavaScript Closure: What is it & How do you use it?

Discover how closures work and ways you can use them to enhance the code you create for your software.

blog.hubspot.com