How to avoid access mutable variable from closure

前端 未结 6 2022
醉梦人生
醉梦人生 2020-12-02 20:10

I have some code like this:

for(var id=0; id < message.receiver.length; id++){
   var tmp_id = id;
   zlib.gzip(JSON.stringify(message.json), function(err         


        
6条回答
  •  醉话见心
    2020-12-02 20:57

    here a simplification of user24359's great answer. This is the solution:

    var object = {a:1,b:2};
    
    for (var y in object){
        (function(){const yyy = y;
            setTimeout(function(){console.log(yyy)},3000);})();
    }
    

    The above code logs a b and is the solution. The following code logs b b :

    var object = {a:1,b:2};
    for (var y in object){
    
        setTimeout(function(){console.log(y)},3000);
    }
    

提交回复
热议问题