Closure ( : 폐쇄 )
외부함수의 변수에 접근할 수 있는 내부함수
function Scope 밖에서도 function Scope 안의 Local Variable 에 접근하기 위해서
☢️ Cf
함수 밖에서 선언된 변수는 함수안에서 사용이 가능하다
자바스크립트가 lexical scoping 을 사용했기 때문
함수 안의 변수는 함수 밖에서 접근할 수 없지만 함수 밖에서 선언된 변수는 안에서 접근이 가능하다.
function multiply(x) {
return function(y)
{
return x*y;
}
}
let three = multiply(3);
three(5); // 15
three(8); // 18
// react 에서 사용예시
const handleAnimalType = React.useCallback(
// 변수 type 을 가지고 있는 closure 함수를 생성해
// onClick 에 적용
(type: animalType) => () => {
ageInfoObjct.type = type
ageInfoObjct.size = null
ageInfoObjct.result = false
onInputAgeInfo(ageInfoObjct)
},
[animalAgeInfo]
)
//.....
onClick={handleAnimalType('강아지')}
내부함수가 선언되면 외부함수의 변수, 인자를 내부함수의 closure 객체에 저장
외부함수를 호출하지 않고 내부함수만 호출하여 외부함수에 지역변수로 설정된 변수에 접근, 사용할 수 있다.
변수를 함수 scope 안쪽에 넣어서 함수 밖으로 노출시키지 않는 방법
class 에서 private, protected 같은 느낌
function drinkPrice()
{
let count = 0;
return {
increase : function()
{
count++;
},
decrease : function()
{
count--;
},
check : function()
{
return count*1000 + '원';
}
}
}
let price = drinkPrice();
price.increase();
price.increase();
price.increase();
price.check(); // 3000원