Javascript 闭包 - 无法在 IIFE 函数中保存“count”的副本

Javascript Closures - Unable to save copy of "count' within an IIFE function

所以我有一个名为 count 的全局变量,它在两个函数声明之间从 0 变为 4(请参阅 myFuncs 数组)。

我想创建一个闭包并为第一个函数保存计数为 0 的副本,为第二个函数保存计数为 4 的副本。

不知何故,即使我正在使用 IIFE(立即调用的函数表达式)创建新的词法范围并使用 (as j) 保存 count 的副本,它们仍然指向 count = 4,因此当函数被执行,第一个和第二个函数在我预期的时候都打印出 "My value: 4" 两次:

"My value: 0" "My value: 4"

var myFuncs = {};

var count = 0;

myFuncs[0] = function(){
    (function(){
        var j = count; //create a closure over the count value and save it inside the IIFE scope
        console.log("My value: " + j); //expecting j to be 0
    })();
}

count = 4;  //Update value inbetween two function declarations

//same as above but the j here should be 4
myFuncs[1] = function(){
    (function(){
        var j = count; //create a closure over the count value and save it inside the IIFE scope
        console.log("My value: " + j);
    })();
}

myFuncs[0](); //My value: 4
myFuncs[1](); //My value: 4

您实际上并没有使用该变量创建闭包,因为您在函数中引用了它。需要传入,传入的值需要使用

        myFuncs[0] = function(j){
            return function(){
                console.log("My value: " + j);
            };
        }(count);