你应该这样做:
var o = {};
for(var i = 0; i < 5; i++) {
(function(i) { // <- self-executing anonymus function with a parameter i
o[i] = function() {
console.log(i); // <- i here will be the argument i,
// not the i from the loop
};
})(i); // <- pass i as an argument
}
o[3]();
会发生什么事是你创造的东西叫做关闭以保持我的状态。
封闭意味着内部函数保持对外功能基准等获得访问其变量和参数(外功能返回甚至之后)。
甲琐碎例如用于闭合是:
function outer(arg) {
var variable = 5;
arg = 2;
function inner() {
alert(variable); // <- the inner function has access to the variables
alert(arg); // and parameters of the outer function
}
}
自动执行(自我呼叫,或立即)函数是一个被称为它被声明后右功能。
(function() {
alert("executed immediately");
})();
两者的结合,事实上,只有函数有范围在Javascript中,导致你上面提到的创建范围一个新的功能,不断的我状态的技术,否则将由内部功能改变,因为关闭。
谢谢你这个工作。 – fent 2010-07-11 10:14:09