可以从闭包中访问JS Mutable Variable [英] JS Mutable Variable is accessible from closure

查看:89
本文介绍了可以从闭包中访问JS Mutable Variable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在我的JS编译器中收到了警告,但是你能告诉我这是否会影响我的代码执行方式吗?

so I've got a warning in my JS compiler but could you explain to me if this will actually affect the way my code will execute?

for (x = 0; x < levels.length; x++) {
    var level = levels[x];
    var candlesOnLevel = $.grep(relevantCandles, function(candles, index) {
        return parseInt($(candles).css("top").replace(/px/, "")) === level;
    });
}


推荐答案

你为什么得到警告

正如@RGraham在评论中提到的那样,js编译器假设第二个参数为 $。grep()是一个回调函数,并且是异步执行的(至少它是语法)。然而这不正确,因为第二个功能实际上是一个过滤功能。请参阅 API文档

As @RGraham mentioned in comments, the js compiler is assuming that second parameter to $.grep() is a callback function and is being executed asynchronously(atleast this is what it look like syntactically). However thats not true because the second function is in-fact a filter function. See the API docs

一个通常在for循环中使用 async 函数
时,可以从闭包获取警告可变变量。那是因为整个 for loop 有一个范围。这意味着在每次迭代中,您最终都会捕获相同的变量。因此回调将得到错误的ID,因为在调用回调之前, level (可变)将被更改。幸运的是,那不是你正在处理的情况(因为$ .grep不是异步):)

One usually get the warning Mutable Variable is accessible from closure when using an async function inside a for loop. Thats because the entire for loop has one scope. That means on each iteration, you would end up capturing the same variable. So the callback will get the wrong ids, because level(being mutable) will be changed before the callback is called. Fortunately, thats not the case you are dealing with(because $.grep is not async) :)


...你能解释一下吗?如果这实际上会影响我的代码
将执行的方式?

...could you explain to me if this will actually affect the way my code will execute?

不,这样的警告不会影响你的结果代码。

No, such warning wont affect the outcome of your code.

您可以忽略警告,但如果您仍想避免这种情况,可以将内容放入封闭内。

You can simply ignore the warning but if you still want to avoid this, you can put the contents inside a closure.

for (x = 0; x < levels.length; x++) {
   (function(){
       var level = levels[x];
       var candlesOnLevel = $.grep(relevantCandles, function(candles, index) {
           return parseInt($(candles).css("top").replace(/px/, "")) === level;
       });
   })();
}

这篇关于可以从闭包中访问JS Mutable Variable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆