Javascript Closures - Unable to save copy of "count' within an IIFE function -
so have global var called count changes 0 4 in between 2 function declarations (see myfuncs array).
i want create closure , save copy of count of 0 1st function , 4 in 2nd function.
somehow, though i'm using iife (immediately invoked function expressions) create new lexical scope , saving copy of count (as j), still both pointing count = 4 , when functions executed, first , second function both print out "my value: 4" twice when expected:
"my value: 0" "my value: 4"
var myfuncs = {}; var count = 0; myfuncs[0] = function(){ (function(){ var j = count; //create closure on count value , save inside iife scope console.log("my value: " + j); //expecting j 0 })(); } count = 4; //update value inbetween 2 function declarations //same above j here should 4 myfuncs[1] = function(){ (function(){ var j = count; //create closure on count value , save inside iife scope console.log("my value: " + j); })(); } myfuncs[0](); //my value: 4 myfuncs[1](); //my value: 4
you're not creating closure variable, because refer in function. needs passed in, , passed in value needs used.
myfuncs[0] = function(j){ return function(){ console.log("my value: " + j); }; }(count);
Comments
Post a Comment