2

Take a look at the following code

//btns is an array passed as a parameter to a function
for(var i = 0, b; b = btns[i]; i++) {
    b.handler = function () {
        var a = btns[i].some_field; //undefined
        //the same for "b.some_field;"
    };
}

Why btns[i] is undefined?

PS. the code adds click handler on extjs buttons if that matters.

putvande
  • 15,068
  • 3
  • 34
  • 50
Eugeny89
  • 3,797
  • 7
  • 51
  • 98

2 Answers2

4

This happens because by the time the inner function is called (which is after the loop is done) the value of i would be btns.length and therefore the value of btns[i] would be undefined.

You need to close over the value of i like this:

b.handler = function(i) {
    return function() {
        var a = btns[i].some_field;
    }
}(i);

It's important to note that although the variables have the same name, they're different variables; i.e. the inner variable shadows the outer, thereby "fixing" the value.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0
for(var i = 0, b; b = btns[i]; i++) {
  b.handler = function () {
    var a = this.btns[i].some_field; 
    //the same for "b.some_field;"
  };
}

give "this." in side the function we have to use "this" to point

backtrack
  • 7,996
  • 5
  • 52
  • 99
  • Do you mean `this.some_field`? Because `b` *is* `btns[i]`. I don't think that each element in the array has a reference back to the array. Anyways, whether this works depends on *how* `b.handler` is called, which we don't know about. – Felix Kling Aug 12 '13 at 07:39