
๐ "Javascript Closure"์ด ๊ธ์ ์ฝ๊ณ ๋๋ฉด ๋ง์นจ๋ด ๋ฌด์์ธ์ง ์ ์ ์์ ๊ฒ ๊ฐ์์
2022-10-19 last update
11 minutes reading beginners javascript frontend programming๐ ๊ธฐ๋ฅ ์ค ๊ธฐ๋ฅ
โผ ํจ์์์ ์๋ฐ์คํฌ๋ฆฝํธ์์ ํจ์๋ฅผ ์ ์ธํ ์ ์์
function outer(){
function inner(){
alert("poland");
}
}
outer(); // unfortunately, nothing happens
โผ ๋ด๋ถ ํจ์๋ฅผ ์คํํ๊ธฐ ์ํด ๋ค์๊ณผ ๊ฐ์ด ์์ฑํ ์ ์์ต๋๋ค.
function outer(){
function inner(){
alert("poland");
}
inner() // here !!!!!
}
outer() // "poland" !
๐ ์ต๋ช ๊ธฐ๋ฅ
์ง๊ธ ์คํ ์์๋
- execute outer()
- declare inner()
- execute inner()
๋ฒ๊ฑฐ๋กญ์ฃ ? ๐
์, ์ต๋ช ํจ์๋ก
alert("poland")
๋ ์งง๊ฒ ์คํํ ์ ์์ต๋๋ค.( function(){ alert("poland"); } )(); // "poland"
๐ ํจ์๋ฅผ ๋ฐํํ๋ ํจ์
(2๋ถ ์์ ๋ง์นจ๋ด ํด๋ก์ ๊ฐ ๋ฌด์์ธ์ง ์ ์ ์์ต๋๋ค)
โผ ํจ์๋ Javascript์์ ํจ์๋ฅผ ๋ฐํํ ์ ์์ต๋๋ค.
function outer(){
var inner = function (){
alert("poland");
}
ใใreturn inner;
}
var func = outer();
func();// "poland"
โผ ์กฐ๊ธ ๋ณํํ๊ณ ๋ด๋ถ ๊ธฐ๋ฅ์ ์ ์์ ์ผ๋ก ์ ์
function outer(){
function inner (){ //** here
alert("poland");
}
ใใreturn inner;
}
var func = outer();
func();// "poland"
โผ ์ด์ inner()๋ฅผ ์ญ์ ํ๊ณ ์ต๋ช ํจ์๋ฅผ ์ฌ์ฉํฉ๋๋ค.
function outer(){
return function(){ //** here
alert("poland");
}
}
var func = outer();
func();// "poland"
โผ ๊ทธ๋ฐ ๋ค์ ์กฐ๊ธ tranfrom ๊ฒฝ๊ณ ๊ธฐ๋ฅ ์ ์ ๋ฌธ์์ด "ํด๋๋"๋ฅผ ์ ์ธํฉ๋๋ค.
function outer(){
return function(){
var country = "poland"
alert(country);
}
}
var func = outer();
func();// "poland"
โผ -- โญ ์ค์!! -- ๋ง์นจ๋ด var country๋ฅผ ์ธ๋ถ ๋ด๋ถ ์ต๋ช ํจ์๋ก ์ด๋
function outer(){
var country = "poland"
return function(){
/** โญ โญ โญ โญ โญ โญ โญ โญ
looks like we can't see country
because country is declared outside anonymous function.
But we can see it, this is typical closure
โญ โญ โญ โญ โญ โญ โญ โญ **/
alert(country);
}
}
var func = outer();
func();// "poland"
console.log(country) // โญ undefined because of scope
โผ ์ด ๋์ผ๋ก ์ฝ๊ฒ ๋ณผ ์ ์์ต๋๋ค

๐ ์ค์ํ ์ 1
ํ์์ ๋ํ ์ผ๋ฐ์ ์ธ ์ง๋ฌธ์ด ์์ต๋๋ค.
define function that return 1,2,3... each time you call it
๋ฉด์ ์์ ๋ฌผ์ด๋ด๋ ์ด์ํ์ง ์์
function outer(){
var num = 1;
returnใfunction (){
alert(num);
x ++;
};
}
var func = outer();
func(); // 1
func(); // 2
func(); // 3
console.log(num) //undefined
๊ทธ๋ฆฌ๊ณ ์ค์ํ ๊ฒ์ด ํ๋ ๋ ์์ต๋๋ค.
๊ทธ ์ฝ๋์์ ๋ณผ ์ ์๋ฏ์ด "num"์ ์ธ๋ถ ํจ์๋ฅผ ํธ์ถํ ์ ์์ผ๋ฏ๋ก ํด๋ก์ ๋ฅผ ํตํด ๊ฐ์ธ ๋ณ์์ ๊ฐ์ ๊ฒ์ ๋ง๋ค ์ ์์ต๋๋ค.
๐ ์ค์ํ ์ 2
์์งํ ์ 1์ "์ค์ํ"์๋ฅผ ์ ์ํ๊ธฐ๊ฐ ์ด๋ ต์ต๋๋ค. ์ด ์ง์์ ์๋ ๊ฒ์ด ์ค์ํ์ง๋ง ๋ง์ ๋๋ค.
ํ์ง๋ง ์ด์ ๋ ๋ง์ ์ค์ ์ฌ๋ก๋ฅผ ๋ณด์ฌ ๋๋ฆฌ๊ฒ ์ต๋๋ค.
์ด๊ฒ์ ์ผ๋ฐ์ ์ธ jquery ์ฝ๋์ ๋๋ค.
// anonymous function
$('.button').click(function(){
alert('Hi!');
});
๊ทธ๋ฌ๋ฉด 2๋ฒ ์ด์ ํด๋ฆญ์ ๋ฐฉ์งํ๋ ๊ธฐ๋ฅ์ ๋ง๋ค ์ ์์ต๋๋ค.
$(function(){
var isClicked = false;
$('.button').click(function(){
if (isClicked) {
alert('you have already clicked once !!');
return false;
}
isClicked = true;
});
});
์ฝ์ด ์ฃผ์ ์ ๊ฐ์ฌํฉ๋๋ค :)
์ฐธ์กฐ:
https://qiita.com/takeharu/items/4975031faf6f7baf077a
http://dqn.sakusakutto.jp/2009/01/javascript.html