我希望有人能向我解释下面的代码中发生了什么。我发现很难包围我的头,为什么这个封闭对待原始信息和引用的方式不同。我希望我在这里失去一些明显的东西。Javascript关闭:原始与参考行为
function returnFunction(x, y) {
return function() {
alert("x:" + x + " - nb of elements in y:" + y.length);
};
}
var f = 0;
var g = [];
var h = [];
for(var i = 0; i < 3; i++) {
f += 1;
g.push(i);
h.push(returnFunction(f, g));
}
for(var i = 0; i < 3; i++) {
h[i]();
}
// this is what gets returned
// x:1 - nb of elements in y: 3
// x:2 - nb of elements in y: 3
// x:3 - nb of elements in y: 3
// why do x and y get treated differently by js in this case?