Skip to content

Instantly share code, notes, and snippets.

@Bambina-zz
Created July 20, 2015 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bambina-zz/98e6a9933dd870a3a989 to your computer and use it in GitHub Desktop.
Save Bambina-zz/98e6a9933dd870a3a989 to your computer and use it in GitHub Desktop.
js closure
function counter(){
var i = 0; //ローカル変数iを定義する。counter関数内のみ参照できる。
return function(){ //無名関数を返す。
return ++i; //iに1を足した結果を返す処理。
}
}
var x = counter(); //変数xに関数counterの実行結果を代入する。関数counterは実行するとローカル変数iを定義し、無名関数を返す。よって変数xには「ローカル変数iに、1を足した結果を返す処理を持つ無名関数」が代入される。
x(); //=>1 無名関数を実行する。ローカル変数iに、1を足した結果が返る。
x(); //=>2 変数xを実行するたびにiの値が増えていく。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment