FrontEnd/Vanilla JS
[JS] 클로저 - closures
펭긴킴
2024. 3. 5. 17:31
https://developer.mozilla.org/ko/docs/Web/JavaScript/Closures
클로저 - JavaScript | MDN
클로저는 주변 상태(어휘적 환경)에 대한 참조와 함께 묶인(포함된) 함수의 조합입니다. 즉, 클로저는 내부 함수에서 외부 함수의 범위에 대한 접근을 제공합니다. JavaScript에서 클로저는 함수 생
developer.mozilla.org
클로저란 ?
- 함수의 조합/ 모임 이라고 할수있겠다.
- 폐쇠된 공간을 만드는 테크닉이다.
- 함수 안의 함수 > 내부 함수를 제외하고는 접근할수가 없다.
function makeAdder(x) {
let y = 1;
return function(z) {
y = 100;
return x + y + z;
};
}
let add5 = makeAdder(5);
let add10 = makeAdder(10);
//클로저에 x와 y의 환경이 저장됨
console.log(add5(2)); // 107 (x:5 + y:100 + z:2)
console.log(add10(2)); // 112 (x:10 + y:100 + z:2)
클로저를 실제로 사용 하는 테크닉 : 쓰로들링 Throttling
function throttle(mainFunction, delay) {
let timerFlag = null; // Variable to keep track of the timer
// Returning a throttled version
return (...args) => {
if (timerFlag === null) { // If there is no timer currently running
mainFunction(...args); // Execute the main function
timerFlag = setTimeout(() => { // Set a timer to clear the timerFlag after the specified delay
timerFlag = null; // Clear the timerFlag to allow the main function to be executed again
}, delay);
}
};
}
// Define a function that fetches some data from an API
function fetchData() {
console.log("Fetching data...");
// Simulate an API call with a random delay
setTimeout(() => {
console.log("Data fetched!");
}, Math.random() * 1000);
}
// Throttle the fetchData function with a delay of 5000 ms
const throttledFetchData = throttle(fetchData, 5000);
// Add an event listener to the window scroll event that calls the throttledFetchData function
window.addEventListener("scroll", throttledFetchData);
코드에 대한 내용 :
코드의 주요기능 : 예민하게 반응 하는 스크롤 > 이것의 감지를 줄여줌.
코드를 천천히 읽어 순서를 잘 살펴 보자.
throttle() 함수를 잘 살펴보면
일단 let timerFlag = null; 로 timerFlag 를 null로 초기화 하였다.
이 함수가 종료가 되려면 ( === return이 되려면) 조건이있는데,
timerFlag = setTimeout(() => {
timerFlag = null;
}, delay);
timerFlag 가 null 이 될려면 setTimeout 함수가 delay 만큼 되어야 timerFlag 가 null 이된다.
(참고로 setTimeout() 은 delay가 랜덤하게 설정된다 (Math.random()), 콜백함수를 차단한다)
timerFlag 가 null 이 아니면 , mainFunction을 실행시킨다.
결론
지금 당장은 이론적으로 완벽하게 이해하기 힘들것이다.
클로져와 클로져를 쓸수 있는 기술이 쓰로틀 이라는 것을 기억하고 ,
기능 구현할시 혹은 작게 나마 복습할때
console.log를 찍어가며 흐름을 파악하자.
폐쇠된 공간을 만든다는것, 함수와 함수의 모임 이라는것, 내부 함수외에는 접근 할수 없다는것을 기억하자
무한 스크롤 구현할때 알 수 있을것!