#1701 JS: closures not working properly

jessevdam Wed 16 Nov 2011

The following codes shows that the closures are not working properly

|->|[] test := [,]
testcount := 0
//here closures does not work all 10 will print 10
while(testcount < 10)
{
  testcount = testcount + 1
  otherval := "" + testcount
  test.add(|->|{
    echo("1 -> " + otherval)
  })
}    
testcount = 0
//here is a fix we make an extra parent closure and the we get the expected count from 1 to 10
while(testcount < 10)
{
  //here we create an extra closure block
  temp := |->|
  {
    testcount = testcount + 1
    otherval := "" + testcount
    test.add(|->|{
      echo("1 -> " + otherval)
    })
  }
  temp()
}     
test.each 
{
  it()
}   

This has been tested on chrome, do not know what the other browser do with it

andy Wed 16 Nov 2011

That looks like #1468 - has to do with how JavaScript implements variable access in functions. Workaround in JavaScript is to wrap in another function - which is essentially what you've done at the Fantom level. I believe there should be a compiler fix we can make there.

Login or Signup to reply.