Unable to save copy of "count' within an IIFE function
So I have a global var called count which changes from 0 to 4 in between two function declarations (see myFuncs array).
I want to create a closure and save a copy of count of 0 for the 1st function and 4 in the 2nd function.
Somehow, even though I'm using IIFE (Immediately Invoked Function Expressions) to create new lexical scope and saving the copy of count with (as j), they are still both pointing to count = 4 and thus when the functions are executed, the first and second function both print out "My value: 4" twice when I expected:
"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
You're not actually creating a closure with that variable, because you refer to it in the function. It needs to be passed in, and that passed in value needs to be used.
myFuncs[0] = function(j){
return function(){
console.log("My value: " + j);
};
}(count);
链接地址: http://www.djcxy.com/p/51618.html