클로저
클로저에 대해 정리하기전 목차를 정하고 정리한다.
<!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'); function increase() { // 카운트 상태를 유지하기 위한 지역 변수 var counter = 0; return ++counter; } incleaseBtn.onclick = function () { count.innerHTML = increase(); }; </script> </body> </html>function Counter() { // 카운트를 유지하기 위한 자유 변수 var counter = 0; // 클로저 this.increase = function () { return ++counter; }; // 클로저 this.decrease = function () { return --counter; }; } var counter = new Counter(); console.log(counter.increase()); // 1 console.log(counter.decrease()); // 0


Last updated