반응형
JavaScript Closures를 이용해 private variable을 구현할 수 있다.
const add = (function () {
let counter = 0;
return function () {counter += 1; return counter}
})();
add();
add();
add();
// the counter is now 3
self-invoking function은 한 번만 호출되며, counter 값을 0으로 설정하고 function expression을 반환해 add에 저장한다.
add는 함수가 되며, 부모 scope에 있는 counter 값에 접근할 수 있다. 이를 closure라 부른다. counter는 익명함수에 의해 protect되며, add 함수만을 이용해 변경될 수 있다.
closure는 부모 스코프에 접근할 수 있는 함수이다.
반응형
댓글