如何避免从闭包访问可变变量 [英] How to avoid access mutable variable from closure
问题描述
我有一些这样的代码:
for(var id=0; id < message.receiver.length; id++){
var tmp_id = id;
zlib.gzip(JSON.stringify(message.json), function(err, buffer){
...
pushStatusPool[message.receiver[tmp_id]] = null; // fix memory leak
delete pushStatusPool[message.receiver[tmp_id]];
...
});
}
我收到一个警告,在闭包中使用 tmp_id
可能会导致问题,因为它是一个可变变量.
And I got a warning that using tmp_id
in closure may cause problem because it is a mutable variable.
我怎么能避免这种情况?我的意思是我怎么能发送一个不可变的变量给回调,因为这是一个 for 循环,我不能更改 zlib.gzip
的代码?或者换句话说,我如何将参数传递给闭包?
How could I avoid that? I mean how could I send an immutable variable to callback since this is a for loop and I can not change code of zlib.gzip
? Or in other words, how could I pass a argument to a closure?
推荐答案
您需要创建一个范围,以使用自执行函数正确捕获 tmp_id
.那是因为整个 for 循环是一个作用域,这意味着每次通过,您都在捕获相同的变量.所以回调会以错误的 id 结束,因为 temp_id
的值会在回调被调用之前改变.
You need to create a scope to correctly capture tmp_id
using a self-executing function. That's because the entire for loop is one scope, meaning each time through, you're capturing the same variable. So the callback will end up with the wrong ids, because temp_id
's value will get changed before the callback is called.
不过,我会忽略(或关闭)警告,这似乎在抱怨,因为 temp_id
是可变的,您可能会重新分配它.这有点傻.如果您真的想修复它,请尝试使用 const
关键字而不是 var
.
I'd ignore (or shut off) the warning, though, which seems to be complaining that because temp_id
is mutable, you might reassign it. That's sort of silly. If you really want to fix it, try using the const
keyword instead of var
.
for(var id=0; id < message.receiver.length; id++){
(function(){
const tmp_id = id;
zlib.gzip(JSON.stringify(message.json), function(err, buffer){
...
pushStatusPool[message.receiver[tmp_id]] = null; // fix memory leak
delete pushStatusPool[message.receiver[tmp_id]];
...
});
})();
}
这篇关于如何避免从闭包访问可变变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!