Jump to content


Check out our Community Blogs

An Alien

Member Since 05 Jan 2011
Offline Last Active Sep 11 2017 11:24 PM
*****

Topics I've Started

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

11 September 2017 - 10:42 PM

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"

 

Code:


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