Closure
์ธ๋ถ ํจ์์ ๋ณ์์ ์ ๊ทผํ ์ ์๋ ๋ด๋ถ์ ํจ์๋ฅผ closure ๋ผ๊ณ ํฉ๋๋ค. closure๋ ์ง์ญ ๋ณ์ ์ ์ธ๋ถ ํจ์์ ๋ณ์, ์ ์ญ ๋ณ์ ์ ์ ๊ทผํ ์ ์๋ ๊ถํ์ ๊ฐ์ง๊ณ ์์ต๋๋ค.
์๋ฐ ์คํฌ๋ฆฝํธ์์ closure๋ ํจ์ ๋ด๋ถ์ ํจ์๋ฅผ ์์ฑ๋ ๋๋ง๋ค ํจ๊ป ์์ฑ๋ฉ๋๋ค.
(ex)
๋ด๋ถ ํจ์(innerFunc())์์ ์ธ๋ถ ํจ์(outerFunc())์ ์ง์ญ ๋ณ์ outerVar์ ์ ์ญ ๋ณ์ globalVar์ ์ ๊ทผํ ์ ์๊ธฐ ๋๋ฌธ์ ๊ฒฐ๊ณผ ๊ฐ์ "global/ outer/ inner"
let globalVar = "global/"; //* ์ ์ญ ๋ณ์ function outerFunc() { let outerVar = "outer/"; //* ์ธ๋ถ ๋ณ์ function innerFunc() { let innerVar = "inner"; //* ๋ด๋ถ ๋ณ์ console.log(globalVar, outerVar, innerVar); } innerFunc(); } outerFunc(); // global/ outer/ inner //* closure: innerFunc()๋ฐ๋ฉด์, ์ธ๋ถ ํจ์(outerFunc())์ ์ ์ญ์์๋ ๋ด๋ถ ํจ์(innerFunc())์ ๋ณ์ innerVar์ ์ ๊ทผํ ์ ์์ต๋๋ค.
let globalVar = "global/"; //* ์ ์ญ ๋ณ์ function outerFunc() { let outerVar = "outer/"; //* ์ธ๋ถ ๋ณ์ function innerFunc() { let innerVar = "inner"; //* ๋ด๋ถ ๋ณ์ } console.log(innerVar); // Error: innerVar is not defined } console.log(innerVar); // Error: innerVar is not defined //* closure: innerFunc()
Closure Example
ํด๋ก์ ๋ฅผ ํตํด ์ํ๋ ์์ ์ ๋ด๋ถ ํจ์๋ฅผ ์คํํ ์ ์์ต๋๋ค.
ํด๋ก์ ๋ ์ฃผ๋ก private data๋ฅผ ์ ์ฅํ๊ณ , ์ ๊ทผํ๋๋ฐ ์ฌ์ฉ๋ฉ๋๋ค. (private ๋ณ์)
getPassword๋secretํจ์ ๋ด์์ ์ ์๋password์ ์ ๊ทผ ๊ฐ๋ฅํ ๋ด๋ถ ํจ์(closure) ์ ๋๋ค. ๋ฐ๋ผ์ ์ด๋ฐ ํจ์๋ฅผ ํน๊ถ ํจ์(privileged function) ๋ผ๊ณ ๋ถ๋ฅด๊ธฐ๋ ํฉ๋๋ค.
โป Reference
[Javascript] Closure, Hoisting (ํด๋ก์ , ํธ์ด์คํ )
Master the JavaScript Interview: What is a Closure?
A simple guide to help you understand closures in JavaScript
[๋ฒ์ญ] ์๋ฐ์คํฌ๋ฆฝํธ ์ค์ฝํ์ ํด๋ก์ (JavaScript Scope and Closures)
Javascript Closure? ํด๋ก์ ? ๊ทธ๋ฆฌ๊ณ ํด๋ก์ ์ฌ์ฉํด module์ ๋ง๋ค๊ธฐ!
Last updated