클로저

:D ·2021년 11월 30일
0

JavaScript✌️

목록 보기
6/14
post-thumbnail

📌 You don't know JS와 https://poiemaweb.com/ 를 참고하여 작성한 글입니다.

클로저란 무엇인가요?! 🤔

클로저는 함수가 속한 렉시컬 스코프를 기억하여 함수가 렉시컬 스코프 밖에서 실행될 때에도 이 스코프에 접근할 수 있게 하는 기능을 뜻합니다.

클로저를 사용하는 이유는 무엇일까?

클로저는 자신이 생성될 때의 환경을 기억해야 하므로 메모리 차원에서 손해를 볼 수 있습니다. 그런데 사용하는 이유가 무엇일까요?!!

1. 상태 유지 : 현재 상태를 기억하고 변경된 최신 상태를 유지할 수 있다.

<!DOCTYPE html>
<html>
<body>
  <button class="toggle">toggle</button>
  <div class="box" style="width: 100px; height: 100px; background: red;"></div>

  <script>
    var box = document.querySelector('.box');
    var toggleBtn = document.querySelector('.toggle');

    var toggle = (function () {
      var isShow = false;

      // ① 클로저를 반환
      return function () {
        box.style.display = isShow ? 'block' : 'none';
        // ③ 상태 변경
        isShow = !isShow; // -> isShow의 상태를 변경할 수 있다.
      };
    })();

    // ② 이벤트 프로퍼티에 클로저를 할당
    toggleBtn.onclick = toggle;
  </script>
</body>
</html>

2. 전역변수의 사용 억제 : 상태 변경이나 가변 데이터를 피하고 오류를 피하는 안정성을 증가 시킬수 있다.

<!DOCTYPE html>
<html>
  <body>
  <p>클로저를 사용한 Counting</p>
  <button id="inclease">+</button>
  <p id="count">0</p>
  <script>
    var incleaseBtn = document.getElementById('inclease');
    var count = document.getElementById('count');

    var increase = (function () {
      // 카운트 상태를 유지하기 위한 자유 변수
      var counter = 0; // -> 전역변수로 사용가능하다...!
      // 클로저를 반환
      return function () {
        return ++counter;
      };
    }());

    incleaseBtn.onclick = function () {
      count.innerHTML = increase();
    };
  </script>
</body>
</html>

3. 정보의 은닉 : 클래스 기반 언어의 private 키워드를 흉내낼 수 있다.

function Counter() {
  // 카운트를 유지하기 위한 자유 변수
  var counter = 0; // -> priavte를 흉내낼 수 있다.

  // 클로저
  this.increase = function () {
    return ++counter;
  };

  // 클로저
  this.decrease = function () {
    return --counter;
  };
}

const counter = new Counter();

console.log(counter.increase()); // 1
console.log(counter.decrease()); // 0
profile
강지영입니...🐿️

0개의 댓글