简体   繁体   English

全局变量在匿名函数中不起作用

[英]global variable not working inside anonymous function

var count = 0; 
for ( var i = 0; i < 4; i++ ) { 
  setTimeout(function(){ 
    assert( i == count++, "Check the value of i." ); 
  }, i * 200); 
}

Why doesnt this work( i comes equal to 4 rather than equal to count every time)? 为什么这项工作不起作用( i等于4而不是每次都等于数)? count, var are created in a global scope so why would they not be available inside the function? count, var是在全局范围内创建的,为什么它们在函数内部不可用?

(I would like an explanation as to why this doesn't work, I found a way to get it to work by wrapping it in another function, just wanting to understand) (我想解释为什么它不起作用,我想办法是通过将其包装在另一个函数中来使它起作用,只是想了解)

Use this; 用这个; Value of i will be 4 inside each setTime out as for loop already finished and value of i的值将在每个setTime内为4,因为循环已经完成并且的值

Anonymous function will preserve variable inside it by creating new context. 匿名函数将通过创建新上下文来在其中保留变量。

var count = 0; 
for ( var i = 0; i < 4; i++ ) { 
  (function(i){
     setTimeout(function(){ 
            assert( i == count++, "Check the value of i." ); 
      }, i * 200);
  })(i); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM