循环内的JavaScript函数 [英] JavaScript Function inside the loop

查看:58
本文介绍了循环内的JavaScript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以通过以下示例向我解释为什么JSLint抱怨循环中的函数":

Can someone explain to me why JSLint complains about "Function inside the loop" with this example:

  for (var i = 0; i < buttons.length; i++) {
    (function(i) {
      buttons[i].onclick = function(e) {
        t.progressBars[t.current].update(buttons[i].getAttribute("data-value"));
      }
    })(i);
  }

但是当我将其更改为:

function makeHandler(i)
  {
    return function() {
        t.progressBars[t.current].update(buttons[i].getAttribute("data-value"));
      }
  }

  for (var i = 0; i < buttons.length; i++) {

      buttons[i].onclick = makeHandler(i);

  }

我不太理解,因为似乎每次循环迭代都必须返回新的函数对象,即使它发生在makeHandler()函数内部.为什么第二个示例对于JS linters来说还可以?

I don't quite understand as it seems that with each loop iteration new function object has to be returned, even though it happens inside of makeHandler() function. Why the second example is ok with JS linters?

推荐答案

您的两个示例不相同.

首先,您要创建一个匿名函数并在每个循环中调用它.

In the first, you are creating an anonymous function and calling it on every loop.

内部函数(单击事件处理程序)很好-您正在分配一个新函数-但是在这种情况下,匿名外部函数效率低下.在您的第二个示例中,外部函数是在循环之外进行重构的,它仅创建一次,而不是buttons.length次.

The inner function (the click event handler) is fine - you're assigning a new function - but it's the anonymous outer function that is inefficient in this context. In your second example the outer function is refactored out of the loop where is it only created once, instead of buttons.length times.

这篇关于循环内的JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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