Created
February 22, 2012 08:03
-
-
Save s-hiroshi/1883350 to your computer and use it in GitHub Desktop.
JavScript > closure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// クロージャーは呼び出し元が関数の変数名解決の環境を保持する。 | |
// そのためクロージャーは呼び出し元から参照できる必要がある。 | |
// 参照の可能性がないものはガーベージコレクションされる。 | |
// クロージャーではない単なる関数 | |
// 呼び出し元に何も帰らないので | |
// hogeを抜けた時点で変数var, incはガーベージコレクションされる | |
function hoge() { | |
var count = 0; | |
function inc() { | |
return count++; | |
} | |
inc(); // incを実行 | |
} | |
var hoge1 = hoge(); | |
console.log(hoge1); // undefined | |
// 典型的なクロージャーの例 | |
// 関数を返す | |
// 呼び出し元は変数名解決の環境を保持する | |
function foo() { | |
var count = 0; // 自由変数 | |
function inc() { | |
return count++; | |
} | |
return inc; | |
} | |
var foo1 = foo(); | |
var foo2 = foo(); | |
console.log(typeof foo1); // function | |
console.log(foo1()); // 0 | |
console.log(foo2()); // 0 | |
console.log(foo2()); // 1 | |
console.log(foo1()); // 1 | |
// オブジェクト型 | |
// 明示的にobjectを返す | |
// 呼び出し元は変数名解決の環境を保持する | |
function bar() { | |
var count = 0; | |
function _inc() { | |
return count++; | |
} | |
return { | |
inc: _inc | |
}; | |
} | |
var bar1 = bar(); | |
var bar2 = bar(); | |
console.log(typeof bar1); // object | |
console.log(bar1.inc()); // 0 | |
console.log(bar2.inc()); // 0 | |
console.log(bar2.inc()); // 1 | |
console.log(bar1.inc()); // 1 | |
// コンストラクタ | |
// 明示的にはreturnされないが内部でインスタンスが返る | |
// 呼び出し元は変数名解決の環境を保持する | |
function Baz() { | |
var count = 0; | |
function _inc() { | |
return count++; | |
} | |
this.inc = _inc; | |
} | |
var baz1 = new Baz(); | |
var baz2 = new Baz(); | |
console.log(typeof baz1); | |
console.log(baz1.inc()); // 0 | |
console.log(baz2.inc()); // 0 | |
console.log(baz2.inc()); // 1 | |
console.log(baz1.inc()); // 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment