【发布时间】:2026-01-09 03:00:01
【问题描述】:
所以我有一个名为 count 的全局变量,它在两个函数声明之间从 0 变为 4(请参阅 myFuncs 数组)。
我想创建一个闭包并为第一个函数保存 0 的副本,在第二个函数中保存 4。
不知何故,即使我使用 IIFE(立即调用函数表达式)来创建新的词法范围并使用(作为 j)保存 count 的副本,它们仍然都指向 count = 4,因此当函数执行后,第一个和第二个函数在我预期的时候都打印了两次“My value: 4”:
“我的价值:0” “我的价值: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
【问题讨论】:
-
像
})(count);一样通过计数并像(function(count){一样接受它
标签: javascript function scope closures iife