var myArrayOfFunctions = [];
for(var i = 0; i<3: i++)
{
//Note how the function being defined uses i,
//where i lives in the parent's scope, this creates a closure
myArrayOfFunctions[i] = function(a) { return a + i;}
}
myArrayOfFunctions[0](5); //Prints 8 WTF!
myArrayOfFunctions[1](5); //8 again
myArrayOfFunctions[2](5); //Well, this 8 was expected
这是因为当函数被“创建”时,它们不复制 i 的值,而是保存对 i 的引用,所以当我们调用函数时,它们使用 i 的当前值,即3。
closure=(function(){
var a=3
var b=5
return function(operation){
return operation(a,b)
}
}())
// The variables a and b are now part of the closure (They are retained even after the outer function returns)
closure(function(x,y){return x+y}) // outputs 8
closure(function(x,y){return x*y}) // outputs 15`