상세 컨텐츠

본문 제목

클로저

Front-End/Javascript

by devloper-jun 2024. 4. 22. 23:43

본문

- 주변 상태(어휘적 환경)에 대한 참조와 함께 묶인(포함된) 함수의 조합. 어떤 함수가 그 주변의 상태를 나타내는 (어휘된) 함수와 함께 묶이는 것.

function sum() {
	const a = 10
    function innerSum () {
    	const b = 10
        console.log(a + b)
    }
    innerSum() //20
}

sum()

 

- sum 함수 안에 innerSum이 있고, innerSum 함수 안에서는 b 변수를 선언한 뒤 innerSum 함수 외부에 있는 a 변수와 b를 더해서 20을 출력한 것으로, 함수가 이처럼 중첩되어 있는 상황에서 변수의 범위가 어떻게 정의되어 있는지 확인할 수 있다. a 변수의 유효범위는 sum 함수의 전체이고 b 변수의 유효범위는 innerSum의 전체이므로, innerSum은 sum안에 선언되어 있어 a 변수를 사용할 수 있게 된것. 즉, 주변상태(어휘적 환경 or 함수)라는 것은 변수가 함수 내부에서 어디서 선언됐는지를 이야기 하는 것으로 볼 수 있으며, 정적으로 결정된다. 클로저는 이러한 주변상태(어휘적 환경 or 함수)를 조합해 코딩하는 기법.

 

- 스코프: 변수의 유효범위

2024.04.22 - [Front-End/Javascript] - 스코프

 

 

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

 

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 you access to an outer function's scope from an inner function. In JavaScript, closur

developer.mozilla.org

 

관련글 더보기