Doesn't JavaScript support closures with local variables?
        Posted  
        
            by qollin
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by qollin
        
        
        
        Published on 2009-03-13T16:27:24Z
        Indexed on 
            2010/05/21
            8:10 UTC
        
        
        Read the original article
        Hit count: 316
        
I am very puzzled about this code:
var closures = [];
function create() {
  for (var i = 0; i < 5; i++) {
    closures[i] = function() {
      alert("i = " + i);
    };
  }
}
function run() {
  for (var i = 0; i < 5; i++) {
    closures[i]();
  }
}
create();
run();
From my understanding it should print 0,1,2,3,4 (isn't this the concept of closures?).
Instead it prints 5,5,5,5,5.
I tried Rhino and Firefox.
Could someone explain this behavior to me? Thx in advance.
© Stack Overflow or respective owner