π
closure
μ£Όλ³ μν( μ΄νμ νκ²½ )μ λν μ°Έμ‘°μ ν¨κ» λ¬ΆμΈ( ν¬ν¨λ ) ν¨μμ μ‘°ν©
ν¨μκ° μμ μ μ μλ μ€μ½ν( λ²μ ) λ°μμλ μ€μ½ν λ΄μ λ³μλ€μ κΈ°μ΅νκ³ μ κ·Ό κ°λ₯
closure
Lexical Scoping( λ μ컬 μ€μ½ν )
why?
μ μ λ³μ μ¬μ© μ΅μ
μ μ λ³μ μ¬μ©μ μ΅μ ν¨μΌλ‘μ¨ μλμΉ μμ μν λ³κ²½μ΄λ κ°λ³ λ°μ΄ν°λ₯Ό νΌν΄ μ€λ₯λ₯Ό μ€μΈλ€. μ΄λ₯Ό ν΅ν΄ μ½λμ μμ μ±μ΄ μ¦κ°νλ€.
μν μ μ§
λ³μμ νμ¬ μνλ₯Ό κΈ°μ΅νκ³ λ³κ²½λ μ΅μ μνλ₯Ό μ μ§νλλ‘ ν μ μλ€. μ°Έμ‘°λ λ³μλ ν¨μ μ€νμ΄ λλ¬λ€κ³ μ¬λΌμ§μ§ μκ³ κ°μ 'κΈ°μ΅'νλ― μλνλ€.
const counter = () => {
let count = 0;
return function() {
count ++;
return count;
}
}
let useCounter = counter();
console.log(useCounter()); // 1
console.log(useCounter()); // 2
console.log(useCounter()); // 3
μ 보 μλκ³Ό μΊ‘μν
ν΄λμ€ κΈ°λ° μΈμ΄μ private
ν€μλ μ²λΌ νμ©ν μ μλ€.
const keepTheSecret = (secret) => {
let theSecret = secret;
// clousre
return {
getSecret: function() {
return theSecret;
},
setSecret: function(newSecret) {
theSecret = newSecret;
}
};
};
let theSecret = keepTheSecret('this is the secret π€«');
theSecret.getSecret(); // 'this is the secret π€«'
theSecret.setSecret('Actually... π¬')
theSecret.getSecret(); // 'Actually... π¬'
pros and cons
pros
cons
let theSecret = keepTheSecret('this is the secret π€«');
// λ μ΄μ theSecretλ₯Ό μ¬μ©νμ§ μμ κ²½μ°
theSecret = null; // λ©λͺ¨λ¦¬ release, closure μ°Έμ‘° μ κ±°