Closure

100pearlcent·2021년 8월 20일
0

JavaScript

목록 보기
2/22

## Closure = function + environment

closure는 function이 하나 생길 때 마다 같이 하나씩 생성된다.
environment는 함수 자신을 둘러싼, 접근할 수 있는 모든 Scope를 의미한다.

클로저란 내부함수가 외부함수의 지역변수에 접근 할 수 있고, 외부함수는 외부함수의 지역변수를 사용하는 내부함수가 소멸될 때까지 소멸되지 않는 특성을 의미한다.

// higher-order function (고차함수)
function and(x) {
	return function print(y) {
    	return x + ' and' + y;
    };
};

const saltAnd = and('salt');
console.log(saltAnd('pepper')); // salt and pepper
console.log(saltAnd('sugar'));  // salt and sugar

위 코드를 Closure의 관점에서 살펴보자면, and 함수로 만들어진 saltAnd의 Closure는
👉 함수 : print
👉 환경 : x -> "salt"

Closure는 higher-order function을 만드는 데 유용하다.

const waterAnd = and('water');
console.log(waterAnd('juice')); // water and juice

saltAnd와 waterAnd 둘 모두 함수는 같은 print이지만, 각각 주어진 변수가 다르다.
saldAnd는 x가 "salt", waterAnd는 x가 "water"로 바인딩 되어 있다.
👉 둘은 서로 다른 closure를 형성하고 있다.

function foo() {
	function bar() {
    };
  
  	function baz() {
    };
};

foo();

Q. 위 코드의 실행 과정에서 생긴 closure의 개수는?
A. 3 개 foo 1, bar 1, baz 1

function foo() {
	function bar() {
    };
  
  	function baz() {
    };
};

foo();
foo(); // 한 번 더 실행한다면?

Q. 위 코드의 실행 과정에서 생긴 closure의 개수는?
A. 5 개 foo 1, bar 2, baz 2

Closure 예시 - Counter

function getCounter() {
  
	var result = {
    	count: count,
      	total: 0
    };
  
  	function count() {
    	result.total += 1;
    };
  
  	return result;
}

var counterA = getCounter();
counterA.count();
counterA.count();

var counterB = getCounter();
counterB.count();

console.log(counterA.total, counterB.total); // 2 1

➖ counterA : 첫 getCounter 실행 시 만들어진 total과 count로 이루어진 객체
➖ counterB : 두 번째 getCounter 실행 시 만들어진 total과 count로 이루어진 객체

0개의 댓글