javascript 闭包问题

产生闭包的例子:

function getValue(){
                var self = this;
                for (var i = 0; i < 5; i++) {
                    self["getIndex" + i] = function(){
                        alert(i);
                    }
                }
            }
            var arr = [11, 22, 33, 44, 55];
            var a1 = new getValue(arr);
            a1.getIndex1();//结果5
            a1.getIndex2();//结果5
            a1.getIndex3();//结果5
闭包解决:

function getValue(){
                var self = this;
                for (var i = 0; i < 5; i++) {
                    (function(j){
                         self["getIndex" + j] = function(){
                            alert(j);
                        }
                    })(i);
                    //在这里把外部参数i传进去,里面j接受参数i
                }
            }
            var a1 = new getValue();
            a1.getIndex0();//结果11
            a1.getIndex1();//结果22
            a1.getIndex2();//结果33

你可能感兴趣的:(JavaScript,闭包)