0

I have a problem with this for loop

var barClass= document.getElementsByClassName("br");
    for(var i=0;i<barClass.length;i++){
        barClass[i].addEventListener('mousedown',function() {initMagic(this.event,i);},false);
        barClass[i].addEventListener('mouseup',function() {endMagic(this.event,i);},false);
        barClass[i].addEventListener('mousemove',function() {mouMove(this.event,i);},false);
}
function initMagic(e,n){
    alert(n);
}

Because the result of alert(n) is identical to barClass.length any barClass[i] I will get same result?

chiwangc
  • 3,566
  • 16
  • 26
  • 32
  • In short - `function() {initMagic(this.event,i)}` creates a closure over variable `i`, not the current value of `i`. Wrap the contents of your loop in `(function(i) { ... })(i)`. – Amadan May 11 '15 at 02:20
  • Please let me to see. I do not understand you. –  May 12 '15 at 07:43
  • `for(var i=0;i – Amadan May 12 '15 at 07:53
  • I've tried so. But event passes as undefine. –  May 12 '15 at 08:34
  • Ah, right, sorry. `this` will change. So capture it with `var that = this;` at the top, and change `this.event` into `that.event`. Or don't even bother with `this.event` - all handlers will receive the event as their parameter, so you can write `function(evt) { initMagic(evt, i); }` (and so forth). – Amadan May 12 '15 at 08:37
  • very thanks...now go!! could you explain what this means'(function(){})(i)' –  May 12 '15 at 08:47
  • Unfortunately, `this` is a pretty important concept in JavaScript, you should read it [in more depth](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) than a comment on Stack Overflow. If you meant some other "this", you need to be more precise (and also read the answer that was linked as duplicate). – Amadan May 12 '15 at 08:49
  • no.I wanted to know why the function you have insert into round parenthesis and why next you are insert i in round parenthesis –  May 12 '15 at 08:59
  • Already explained in the duplicate question and its answer. Which is precisely the reason why it is marked as duplicate. – Amadan May 12 '15 at 09:13

0 Answers0