- 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, closures are created every time a function is created, at function creation time.
📋 학습 목표
✳️ MDN example code :
function init() { // init 함수는 또 다른 함수를 리턴하고 있으므로 클로저 함수임. const name = 'Mozilla'; // name is a local variable created by init function displayName() { // displayName() is the inner function, a closure console.log(name); // use variable declared in the parent function } } displayName(); } init();
❓ : 내부 함수는 바로 위 외부 함수(부모 함수)의 스코프에만 접근이 가능한가?
⇨ ❌! 내부 함수는 모든 외부 함수 스코프에 접근이 가능함.
내부 함수가 위치한 전체 함수 스코프에도 변수 명이 없으면 전역 스코프(Global scope)까지 탐색함!
(단 같은 이름의 변수가 여러 단계에서 재할당 되었을 경우, 가장 가까운 상위 스코프의 변수명의 값을 가져오고 내부함수가 종료되어 그 이상의 상위 스코프를 탐색하지 않음)
- 전역 스코프에 설정된 'name' 을 참조하는 내부 함수 예시
let name = 'Mozilla'; function init() { function displayName() { return function () { return function () { console.log(name); } } } return displayName()()(); // 결과값 : 'Mozilla' } init();
- var, let, const 는 모두 함수 스코프를 가질 수 있으므로 동일하게 적용됨.
❓ : 내부 함수는 왜, 어떻게 외부 스코프의 변수를 참조 가능한가?
❗️ : 내부 함수 innerFunc()가 호출될 때, 외부 함수 outerFunc()의 환경(Lexical environment)을 기억하고 있기 때문!
즉, 클로저(closure)는 반환된 내부 함수가 자신이 선언(생성)되었을 때의 환경(Lexical environment)인 스코프를 기억하여, 자신이 선언됐을 때의 환경(스코프) 밖에서 호출되어도 그 환경(스코프)에 접근할 수 있는 함수임.
🔗 Closure in JavaScript - scaler.com
const tagMaker = tag => content => `<${tag}>${content}</${tag}>`; const divMaker = tagMaker('div'); console.log(divMaker('hello')); // 결과값 : <div>hello</div> console.log(divMaker()); // 결과값 : <div>undefined</div>
=> 클로저 함수인
tagMaker
에'div'
변수가 저장되어, 외부함수 실행은 끝났지만 계속해서 출력 가능
===> 여기서부턴 내일 정리하자 @_@ 연습문제 풀다보니 아직 제대로 이해가 안되었다! 변수가 어디로 들어가는지 헷갈림...!
📚 추가로 공부할 것 :