Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

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

javascript closure iife scope functions

  • Please log in to reply
No replies to this topic

#1 An Alien

An Alien

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 323 posts
  • Programming Language:Java
  • Learning:C, Java, PHP, Python, JavaScript, Lisp, Transact-SQL, Others

Posted 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


  • 0





Also tagged with one or more of these keywords: javascript, closure, iife, scope, functions