μŠ€ν† λ¦¬
Frontend
πŸ” 클둜져(Closure)에 λŒ€ν•΄μ„œ
Aug. 20, 2021, 3:16 pm.

By Jaekwon Han

Jaekwon Han leads Front-end team at 29CM and has worked as a Front-end developer and an UI designer.

Closure

ClosureλŠ” ν•¨μˆ˜μ™€ ν•¨μˆ˜μ˜ μ‹€ν–‰ ν™˜κ²½(λ˜λŠ” 생성 μ‹œμ— μ£Όμž…λœ μ»¨ν…μŠ€νŠΈ)κ³Ό ν•¨μˆ˜κ°€ λ²ˆλ“€λœ μƒνƒœλ₯Ό λœ»ν•œλ‹€. κ·ΈλŸ¬λ―€λ‘œ ν΄λ‘œμ ΈλŠ” ν•¨μˆ˜ λ°”κΉ₯의 μŠ€μ½”ν”„λ₯Ό ν•¨μˆ˜ μ•ˆμ—μ„œ μ ‘κ·Όν•  수 μžˆλ„λ‘ ν•΄μ£Όλ©°, μžλ°”μŠ€ν¬λ¦½νŠΈμ—μ„œλŠ” ν΄λ‘œμ ΈλŠ” ν•¨μˆ˜κ°€ 생성될 λ•Œ μƒμ„±λœλ‹€.
ν΄λ‘œμ €λŠ” ν•¨μˆ˜μ΄λ‹€. 그것이 μƒμ„±λœ μ»¨ν…μŠ€νŠΈ, 심지어 κ·Έ μ»¨ν…μŠ€νŠΈκ°€ 역할을 λ‹€ν–ˆμ„ λ•Œμ—λ„, κ·Έ μ»¨ν…μŠ€νŠΈμ˜ λ³€μˆ˜λ“€μ— μ ‘κ·Ό ν•  수 μžˆλŠ” ν•¨μˆ˜μ΄λ‹€.
1const init = () => {
2  const prefix = 'Hello' // init의 지역 λ³€μˆ˜
3  function greet(name) { // 클둜져
4    console.log(prefix + ' ' + name) // λΆ€λͺ¨ ν•¨μˆ˜μ˜ λ³€μˆ˜λ₯Ό μ‚¬μš©ν•œλ‹€
5  }
6  
7  return greet
8}
9
10const greet = init()
11greet('Mozilla') // Hello Mozilla
12greet('Google') // Hello Google
μžλ°”μŠ€ν¬λ¦½νŠΈ νŒŒμ„œλŠ” nested된 ν•¨μˆ˜λ“€μ΄ 각자 μ°Έμ‘°ν•˜λŠ” λ³€μˆ˜λ“€μ„ 이처럼 resolveν•œλ‹€. Lexical scopingμ΄λž€ λœ»μ€ μ†ŒμŠ€ μ½”λ“œμ—μ„œ λ³€μˆ˜κ°€ μ •μ˜λœ μœ„μΉ˜λ₯Ό ν†΅ν•΄μ„œ κ·Έ λ³€μˆ˜κ°€ μ‚¬μš©κ°€λŠ₯ν•œ 곳이 μ •μ˜λœλ‹€λŠ” λœ»μ΄λ‹€. nested ν•¨μˆ˜λ“€μ€ λ°”κΉ₯ μŠ€μ½”ν”„μ˜ λ³€μˆ˜λ“€μ— 접근이 κ°€λŠ₯ν•˜λ‹€.
This is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested. The word lexical refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope.

클둜져λ₯Ό μ‚¬μš©ν•˜λŠ” 이유

첫번째 μ΄μœ λŠ” 데이터λ₯Ό λ³΄ν˜Έν•˜κΈ° μœ„ν•΄μ„œμ΄λ‹€. 데이터λ₯Ό λ³΄ν˜Έν•¨μœΌλ‘œμ¨ μš°λ¦¬κ°€ μž‘μ„±ν•œ ν”„λ‘œκ·Έλž¨μ΄ implementation detail은 감좔고 interfaceλ₯Ό μ œκ³΅ν•  수 μžˆλ‹€. (μ „μžκ°€ ν›„μžλ³΄λ‹€ λ³€ν•˜κΈ° 쉽닀)
클둜져λ₯Ό μ‚¬μš©ν•˜λ €λ©΄, λ‹¨μˆœν•˜κ²Œ ν•¨μˆ˜λ₯Ό λ‹€λ₯Έ ν•¨μˆ˜ μ•ˆμ— μ •μ˜ν•˜κ³  λ…ΈμΆœν•˜λ©΄ λœλ‹€.

ν΄λ‘œμ Έκ°€ λ™μž‘ν•˜λŠ” 방식

ν•¨μˆ˜κ°€ 싀행될 λ•Œ, Lexical ν™˜κ²½μ΄ μžλ™μœΌλ‘œ μƒμ„±λœλ‹€. 이곳에 지역 λ³€μˆ˜μ™€ ν•¨μˆ˜ μ‹€ν–‰ μ‹œ μ£Όμž…λœ λ³€μˆ˜λ“€μ΄ μ €μž₯λœλ‹€. ν•¨μˆ˜κ°€ μ‹€ν–‰λ˜λŠ” λ™μ•ˆμ—λŠ” 두 개의 Lexical ν™˜κ²½μ΄ μ‘΄μž¬ν•œλ‹€. ν•¨μˆ˜ 내뢀와 μ™ΈλΆ€. λ³€μˆ˜λ₯Ό μ°ΎλŠ” μˆœμ„œλŠ” λ‚΄λΆ€μ—μ„œ μ™ΈλΆ€ μˆœμ„œμ΄λ‹€.

정리

  • ν΄λ‘œμ ΈλŠ” λ°”κΉ₯ λ³€μˆ˜λ“€μ„ κΈ°μ–΅ν•˜κ³  μ ‘κ·Όν•  수 μžˆλŠ” ν•¨μˆ˜
  • ν•¨μˆ˜μ™€ lexical ν™˜κ²½μ˜ ν•©
  • [[Environment]]λŠ” μ™ΈλΆ€ lexical ν™˜κ²½μ„ μ§€μΉ­ν•œλ‹€.