closure

YeonnΒ·2024λ…„ 6μ›” 10일
0

JavaScript

λͺ©λ‘ 보기
25/26
post-thumbnail

πŸ“ 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

  • λ©”λͺ¨λ¦¬ λˆ„μˆ˜( memory leak ): μ°Έμ‘°λ₯Ό μœ μ§€ν•˜λŠ” λ³€μˆ˜λ“€μ„ 계속 λ©”λͺ¨λ¦¬μ— 남겨두기 λ•Œλ¬Έμ— μ˜λ„μΉ˜ μ•Šκ²Œ λ©”λͺ¨λ¦¬μ˜ λˆ„μˆ˜κ°€ λ°œμƒν•œλ‹€. μ‚¬μš©μ΄ λλ‚œ ν΄λ‘œμ €λŠ” λ©”λͺ¨λ¦¬ λˆ„μˆ˜λ₯Ό 막기 μœ„ν•΄ μ°Έμ‘°λ₯Ό μ œκ±°ν•˜λ„λ‘ ν•œλ‹€.
let theSecret = keepTheSecret('this is the secret 🀫');

// 더 이상 theSecretλ₯Ό μ‚¬μš©ν•˜μ§€ μ•Šμ„ 경우
theSecret = null;  //  λ©”λͺ¨λ¦¬ release, closure μ°Έμ‘° 제거
  • 가독성 μ €ν•˜
  • 디버깅 어렀움

0개의 λŒ“κΈ€

κ΄€λ ¨ μ±„μš© 정보