본문 바로가기

코드스테이츠

Clousures

0. 클로저란? :Closures

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.

 

안에있는 변수가 함수 밖에 있는 변수에 접근이 가능한 것. 이는 안에 있는 함수를 호출하지 않는 이상은 밖에 있는 함수의 수정이 불가능하다는 것을 의미한다. 

 

1. 클로저 함수를 이해하자

function increaseBy(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    const increaseBy3 = increaseBy(3);
    const increaseBy5 = increaseBy(5);

    expect(increaseBy3(10)).to.equal(13);
    expect(increaseBy5(10)).to.equal(15);
    expect(increaseBy(8)(6) + increaseBy(5)(9)).to.equal(28);

1.increaseBy(3)은 함수를 리턴한다.

2.이 함수를 변수 increaseBy3이 할당을 받는다.

3. increaseBy3은 함수이므로 함수에 인자로 10을 넣을 수 있고 

4. increaseBy3의 return 값은 numberToIncrease 즉 10 과 increaBy(3)으로 얻은 값 3은 increaseByAmount가 내부 함수에서 접근할 수 있으므로 3을 얻을 수 있다. 그러므로 10+3  의 결과를 얻을 수 있다.

 

 

 

2. 클로저 함수와 화살표 함수를 같이 이해하자

 

 

    const htmlMaker = tag => textContent => `<${tag}>${textContent}</${tag}>`
    expect(htmlMaker('div')('code states')).to.eql(`<${'div'}>${'code states'}</${'div'}>`)

    const liMaker = htmlMaker('li')
    expect(liMaker('1st item')).to.eql(`<${'li'}>${'1st item'}</${'li'}>`)
    expect(liMaker('2nd item')).to.eql(`<${'li'}>${'2nd item'}</${'li'}>`)

 

 

'코드스테이츠' 카테고리의 다른 글

재귀  (0) 2021.10.06
class의 이해  (0) 2021.10.05
props 의 이해  (0) 2021.09.02
리엑트 2 props && state  (0) 2021.08.17
구조분해할당  (0) 2021.08.17