클로저

함수와 그 함수가 접근할 수 있는 변수의 조합

const globalVar = '전역 변수';

function outerFn() {
  const outerFnVar = 'outer 함수 내의 변수';
  const innerFn = function() { 
    return 'innerFn은 ' + outerFnVar + '와 ' + globalVar + '에 접근할 수 있습니다.';
  }
	return innerFn;
}

데이터를 보존하는 함수

function createFoodRecipe (foodName) {
  const getFoodRecipe = function (ingredient1, ingredient2) {
    return `${ingredient1} + ${ingredient2} = ${foodName}!`;
  }
  return getFoodRecipe;
}

const highballRecipe = createFoodRecipe('하이볼');
highballRecipe('콜라', '위스키'); // '콜라 + 위스키 = 하이볼!'
highballRecipe('탄산수', '위스키'); // '탄산수 + 위스키 = 하이볼!'
highballRecipe('토닉워터', '연태고량주'); // '토닉워터 + 연태고량주 = 하이볼!'

즉, 가장 중요한 포인트는 “할당할 때 매개변수를 전달하면 재할당을 하지 않는 이상, 변경되지 않는다”

커링

여러 전달인자를 가진 함수를 연속적으로 리턴하는 함수로 변경하는 행위

function ShopBasket (types) {
    return function (price) {
        const regexPrice = price.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');
        return function (size) {
            return `고르신 옷의 정보 : ${types} - ${regexPrice}원 / size : ${size}`
        }
    }
}

let clothTypes = ShopBasket("jean");
let clothPrice = clothTypes(29900);
let clothSize = clothPrice("XL");

console.log(clothSize);
// 고르신 옷의 정보 : jean - 29,900원 / size : XL

clothTypes = ShopBasket("sweater");
clothPrice = clothTypes(37900);
clothSize = clothPrice("S");
console.log(clothSize);
// 고르신 옷의 정보 : sweater - 37,900원 / size : S