Closure
โA closure is the combination of a function and the lexical environment within which that function was declared.โ
"ํด๋ก์ ๋ ํจ์๊ฐ ์ ์ธ๋์์ ๋์ ๋ ์์ปฌ ํ๊ฒฝ๊ณผ์ ์กฐํฉ์ด๋ค"
ํด๋ก์ ์ ๋ํด MDN์ ์์ ๊ฐ์ด ์ ์ ๋์ด ์๋ค.
๋ฌด์จ ๋ง์ธ์ง ์ดํด๊ฐ ๋๋๊ฐ??? ํ์๋ ์๋ฌด๋ฆฌ ์๊ฐํด๋ ์ดํด๊ฐ ์๋๋ค.
๊ทธ๋ฌ๋ฉด ์ด๋ ๊ฒ ์ดํด ํ๋ ๊ฒ์ด ์ด๋ค๊ฐ?
๋ด๋ถํจ์๊ฐ ์ธ๋ถ๋ณ์๋ฅผ ์ฐธ์กฐํ๋ ๊ฒ์ ๋งํ๋ค.
์กฐ๊ธ์ ์๋ฟ๋๊ฐ?? ํ๋ฒ ์๋ ์์ ์ฝ๋๋ฅผ ๋ณด๊ณ ํ๋ฒ ์ดํดํด๋ณด์.
function Outer(){
const str = 'hello'
function Inner(){
console.log(str)
}
Inner()
}
Outer() // hello
์์ ์ฝ๋๋ฅผ ๋ณด๋ฉด ์๊ฒ ์ง๋ง, Outer์์ ์๋ Inner ๋ฉ์๋๊ฐ Outer์ ๋ณ์๋ฅผ ํธ์ถํ๊ณ ์๋ค. ์ด์ ๊ฐ์ด ์ข ์กํ์ง ์๋๊ฐ???
๋ ์์ธํ ๋ด์ฉ์ ๋งจ ์๋ ๋ ํผ๋ฐ์ค๋ฅผ ์ฐธ๊ณ ํ์.! ๐
Next) Closure๋ Memory Leak์ ๋ฐ์์ํจ๋ค ?!
๋ด๋ถํจ์๊ฐ ์ธ๋ถ๋ณ์๋ฅผ ์ก๊ณ ์๊ธฐ ๋๋ฌธ์ GC๊ฐ ํด๋น ๋ณ์๋ฅผ ์ฒ๋ฆฌํ์ง ๋ชปํ๋ค. Javascript์์๋ ํด๋น ๋ฌธ๋ฒ์ด ์๋ค. ( Swift์์๋ weak self
๋ฅผ ์ฌ์ฉ์ ํด์ ์์
์ ํ์๋ค.) ๊ทธ๋ฌ๋ฉด Javascript GC์์ ์ด๋ป๊ฒ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ์ก๊ณ ์๋์ง. ์ด๋ป๊ฒ ํด๊ฒฐํด์ผ ํ๋์ง ๋ค์ํธ์์ ๋ณด๋๋ก ํ์.!
๋ค์ ์ฐพ์๋ณด๋ javascript์๋ weak ref๊ฐ ์๊ธดํ๋ค. ๋ค๋ง IE, safari์์ ์ง์ํ์ง ์๋๋ค..
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef
์ฐธ๊ณ
https://poiemaweb.com/js-closure ( ํ์ ๊ธ๋ณด๋ค ๋งค์ฐ ์ ์ค๋ช ๋์ด ์๋ค.)
Last updated
Was this helpful?