
function init() {
const name = "soobin"; // 지역 변수
function test() { // test() 은 내부 함수이며, 클로저다.
console.log(name); // 부모 함수에서 선언된 변수를 사용
}
return test;
}
const inner = init();
inner(); // 'soobin'
const counter = (function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
};
})();
console.log(counter.value()); // logs 0
counter.increment();
counter.increment();
console.log(counter.value()); // logs 2
counter.decrement();
console.log(counter.value()); // logs 1
https://developer.mozilla.org/ko/docs/Web/JavaScript/Closures
https://opentutorials.org/course/743/6544
https://velog.io/@seaworld0125/JavaScript-%ED%81%B4%EB%A1%9C%EC%A0%80-%EA%B7%BC%EB%8D%B0-%EC%9D%B4%EC%A0%9C-%EC%BA%A1%EC%8A%90%ED%99%94%EB%A5%BC-%EA%B3%81%EB%93%A4%EC%9D%B8