클로저가 가장 유용하게 사용되는 상황은 현재상태를 기억하고 변경된 최신상태를 유지하는 것이다.
toggle버튼을 누를때마다 빨간박스의 상태가 변하는 코드를 작성해 보았다.
<!DOCTYPE html>
<html>
<body>
<button class="toggle">toggle</button>
<div class="box" style="width: 100px; height: 100px; background: red;"></div>
<script>
클래스가 box인 엘리먼트를 변수box에 할당
클래스가 toggle인 엘리먼트를 변수 toggleBtn에 할당
버튼의 상태가 어휘적환경에 의해 메모리에 저장될 수 있게
변수명이 toggle인 클로저 함수를 만들고
버튼의 상태를 할당한 변수isShow 만들기
콜백함수에 isShow의 상태에 따라 CSS의 display가 변하는 조건 만들기
toggleBtn 클릭시 toggle함수 실행
</script>
</body>
</html>
<!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 () {
if(isShow){
console.log('on')
box.style.display = 'block'
isShow = !isShow
} else if(!isShow) {
console.log('off')
box.style.display = 'none'
isShow = !isShow
}
};
})();
toggleBtn.onclick = toggle;
</script>
</body>
</html>