0

Possible Duplicate:
Javascript closure inside loops - simple practical example

I seem to be struggling to understand the scope of variables in javascript.

I have the following code:

for (var i =2; i< 5;i++){
    var k = (i+1).toString()
    window['graph.point'+i].onMove = function(x,y){
        return [min(x,window['graph.point'+k].coord[0]],f(min(x,window['graph.point'+k].coord[0]))]}
    }
}

This code is supposed to put some constraints on the possible locations of some movable points I have on a graph. The problem seems to be that when the graph.point objects check to see if the constrain is satisfied, they use the last value of k, which is 6. How do I make sure these objects use the value of k that they are supposed to?

Community
  • 1
  • 1
  • You have an extra end curly bracket in there – Chris Laplante Aug 17 '12 at 02:23
  • Read up on the difference between function expressions and function declarations. Define your function within a closure to preserve the scope. – Cecchi Aug 17 '12 at 02:26
  • @Cecchi: Function definitions and closures don't create scope. Only a function execution creates scope. – Felix Kling Aug 17 '12 at 02:28
  • Correct you are, my mistake with the terminology. What I meant to say is to return the function from a self-executing function... which is certainly different than a closure, thanks for the correction. – Cecchi Aug 17 '12 at 02:37
  • \@ Felix: it appears that you are correct. Should I delete this post? –  Aug 17 '12 at 02:44

1 Answers1

1

for blocks don't have their own variable scope so you need to create a new scope with an immediate function:

for (var i =2; i< 5;i++){
    var k = (i+1).toString();
    (function(k, i) {
        window['graph.point'+i].onMove = function(x,y){
            return [min(x,window['graph.point'+k].coord[0]],f(min(x,window['graph.point'+k].coord[0]))]}
        }
    })(k, i);
}
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471