クロージャーの背後にある基本的な考え方は、クローザーはすべてのローカル データを値でバインドするため、クローザーを使用して、生成された関数のその「インスタンス」に対してのみローカルな変数を初期化してから変更できるということです。
これは宿題のように思えるので、クロージャーを使用して別の質問に答えます。クロージャーを使用して、完全な正方形 (1、4、9 など) を一度に 1 つずつ取得します。
function makeSquareIteratorFunction() {
var squareRoot = 1;
var getNext = function() {
// Calculate the number you need to return
var square = squareRoot * squareRoot;
// Apply side effects. In this case just incrementing the counter, but with
// Fibonacci you will need to be a little more creative :-)
// You might also prefer to do this first. Depends on your approach.
squareRoot = squareRoot + 1;
// Return the value
return square;
};
// Return the function object, which can then be called later
return getNext;
}
// Usage
var getNextSquare = makeSquareIteratorFunction();
alert(getNextSquare()); // 1
alert(getNextSquare()); // 4
alert(getNextSquare()); // 9
makeSquareIteratorFunction
ここで、外側の関数 ( ) で定義されたローカル変数がローカライズされ、クロージャにバインドされていることを指摘する価値があります。したがって、makeSquareIteratorFunction()
複数回呼び出すと、後の呼び出しは最初の呼び出しから独立します。
var getNextSquare1 = makeSquareIteratorFunction();
alert(getNextSquare1()); // 1
alert(getNextSquare1()); // 4
var getNextSquare2 = makeSquareIteratorFunction();
alert(getNextSquare2()); // 1 (!) because it's a new closure, initialized the same way
alert(getNextSquare1()); // 9 (!) because it was "on" 4 last time
うまくいけば、それはそれを少し説明するのに役立ちますか?そうでない場合は、コメントを残してください。:-)