클로저(Closure)

Jaeseok Han·2023년 3월 11일

javascript 문법

목록 보기
8/11

1. 어휘적 환경

function makeAdder(x) {
  return function(y) {
    return x + y;
  }
}

const add3 = makeAdder(3);
console.log(add3(2));

전역 Lexical 환경
makeAddr : function
add3 : function

↑참조

makeAdder Lexical 환경
x : 3

↑참조

익명 함수 Lexical 환경
y : 2

2. Closure

함수와 렉시컬 환경의 조합
함수가 생성될 당시의 외부 변수를 기억
생성 이후에도 계속 접근 가능

function makeCounter (){
  let num = 0; //은닉화
  
  return function() {
    	return num++;
  }
}

let counter = makeCounter();

console.log(counter()); // 0
console.log(counter()); // 1
console.log(counter()); // 2

0개의 댓글