闭包背后的基本思想是,由于关闭器按值绑定所有本地数据,因此您可以使用它们来初始化然后修改仅对生成函数的“实例”本地的变量。
由于这似乎是家庭作业,我将使用闭包来回答一个不同的问题:使用闭包获得完美的正方形(1、4、9 等),一次一个。
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
希望这有助于解释一下?如果没有,请发表评论。:-)