2024.01.04 - [Javascript] - [JavaScript] 클로저(Closures) - 활용편(1/2)
[JavaScript] 클로저(Closures) - 활용편(1/2)
이전 포스팅에서 클로저의 개념을 살펴보았다. 이번 포스팅에서는 배웠던 개념을 바탕으로 클로저의 예시와 활용법에 대해서 알아보고자 한다. 클로저 예시 1 코드 let f; const g = function () { const a
codesmoothie.tistory.com
상기 포스팅에서 연장되는 글입니다.
클로저 예시 코드
const boardPassengers = function(n, wait) {
const perGroup = n / 3;
setTimeout(function(){
console.log(`We are now boarding all ${n} passengers`);
console.log(`There are 3 groups, each with ${perGroup} passengers`)
}, wait * 1000)
console.log(`Will start boarding in ${wait} seconds`)
}
boardPassengers(180, 3);
코드 실행 결과
Will start boarding in 3 seconds
We are now boarding all 180 passengers
There are 3 groups, each with 60 passengers
setTimeout의 콜백 함수는 boardPassengers 함수와는 완전히 별게로 실행되었다. 그런데 콜백 함수는 생성된 변수 환경에 있는 모든 변수를 사용하여 값을 나타내었다. 이는 클로저가 먼저 생성되었다는 명백한 신호이다. 즉, setTimeout의 콜백 함수가 실행된 boardPassengers 함수에서 정의된 변수에 접근할 수 있는 클로저를 만든 것이다. 클로저는 변수와 함께 인수(arguments)도 포함되어 있다. 인수는 함수에서 단순히 지역 변수이기 때문이다.
클로저와 스코프 체인
마지막으로 클로저가 스코프 체인보다 우선한다는 것을 확인해보자.
const boardPassengers = function(n, wait) {
const perGroup = n / 3;
setTimeout(function(){
console.log(`We are now boarding all ${n} passengers`);
console.log(`There are 3 groups, each with ${perGroup} passengers`)
}, wait * 1000)
console.log(`Will start boarding in ${wait} seconds`)
}
const perGroup = 1000;
boardPassengers(180, 3);
'const perGroup = 1000;'이라는 코드가 추가되었다. 스코프 체인이 클로저보다 우선 순위가 있다면 setTimeout의 콜백 함수는 Global Scope에 존재하여 'const perGroup = 1000;' 변수를 사용할 것이다. 하지만, 실행된 콜백함수의 perGroup 값을 살펴본다면 값이 60으로 나온다. 'const perGroup = n / 3;'을 제거하고 실행한다면 perGroup의 값은 1000으로 나온다.
'Javascript' 카테고리의 다른 글
[JavaScript] 호이스팅(hoisting)이란? (1) | 2024.01.30 |
---|---|
코드 에디터를 위한 iframe 디자인 패턴 (0) | 2024.01.10 |
[JavaScript] 클로저(Closures) - 활용편(1/2) (2) | 2024.01.04 |
[JavaScript] 클로저(Closures) - 개념편 (0) | 2024.01.02 |
[JavaScript] 비동기 코드의 동작 원리 - 이벤트 루프(The Event Loop) (2) | 2023.12.29 |