์ธ๋ถ ํจ์์ ๋ณ์์ ์ ๊ทผํ ์ ์๋ ๋ด๋ถ์ ํจ์๋ฅผ closure ๋ผ๊ณ ํฉ๋๋ค. closure๋ ์ง์ญ ๋ณ์ ์ ์ธ๋ถ ํจ์์ ๋ณ์ , ์ ์ญ ๋ณ์ ์ ์ ๊ทผํ ์ ์๋ ๊ถํ์ ๊ฐ์ง๊ณ ์์ต๋๋ค.
์๋ฐ ์คํฌ๋ฆฝํธ์์ closure๋ ํจ์ ๋ด๋ถ์ ํจ์๋ฅผ ์์ฑ๋ ๋๋ง๋ค ํจ๊ป ์์ฑ๋ฉ๋๋ค.
(ex)
๋ด๋ถ ํจ์(innerFunc())์์ ์ธ๋ถ ํจ์(outerFunc())์ ์ง์ญ ๋ณ์ outerVar์ ์ ์ญ ๋ณ์ globalVar์ ์ ๊ทผํ ์ ์๊ธฐ ๋๋ฌธ์ ๊ฒฐ๊ณผ ๊ฐ์ "global/ outer/ inner"
Copy 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์ ์ ๊ทผํ ์ ์์ต๋๋ค.
Copy 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
ํด๋ก์ ๋ฅผ ํตํด ์ํ๋ ์์ ์ ๋ด๋ถ ํจ์๋ฅผ ์คํํ ์ ์์ต๋๋ค.
Copy function studyClosure() {
var name = "closure";
return function () {
console.log("Try to understand", name);
};
}
// ์ํ๋ ์์ ์ ๋ด๋ถํจ์๋ฅผ ์คํํ๊ธฐ ์ํด 'closure'๋ฅผ ํ์ฉํฉ๋๋ค.
// studyClosure ํจ์๊ฐ ์คํ๋๋ฉด, ๋ณ์ myClosure๋ studyClosure์ ๋ด๋ถํจ์๋ฅผ ๊ฐ๋ฆฌํค๊ฒ ๋ฉ๋๋ค.
let myClosure = studyClosure();
myClosure(); // Try to understand closure
ํด๋ก์ ๋ ์ฃผ๋ก private data๋ฅผ ์ ์ฅํ๊ณ , ์ ๊ทผํ๋๋ฐ ์ฌ์ฉ๋ฉ๋๋ค. (private ๋ณ์ )
Copy function secret() {
let password = "***";
return {
getPassword() {
alert(password);
},
};
}
// ๋ด๋ถ ํจ์์ ๋ณ์๋ ์ธ๋ถ์์ ์ ๊ทผํ ์ ์์ต๋๋ค.
console.log(getPassword()); // Error: getPassword is not defined
// ๋ด๋ถ ํจ์์ ๋ณ์๋ฅผ ์ธ๋ถ์์ ์ ๊ทผํ๊ธฐ ์ํด์ 'closure'๋ฅผ ํ์ฉํฉ๋๋ค.
// secret ํจ์๊ฐ ์คํ๋๋ฉด, ๋ณ์ privateVar๋ secret์ ๋ด๋ถํจ์๋ฅผ ๊ฐ๋ฆฌํค๊ฒ ๋ฉ๋๋ค.
const PrivateVar = secret(); // {getPassword: ฦ}
PrivateVar.getPassword();
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์ ๋ง๋ค๊ธฐ!