javascript - 在循环中定义函数的最佳方法是什么? - JavaScript

标签 javascript jquery loops

我想知道哪种方式在循环中定义函数更好?我总是使用第一种方式。这是对的吗?或者这种情况还有另一种方法?

请指导我,我在代码中经常使用第一种方式,我想知道这是真的吗?

$('.elements').each(function(){
  // elements
  var $t = $(this), $anotherEl = $t.find('.el2'), $anotherEl2 = $t.find('.el3');

  // variables
  var isVisble = $t.is(':visible'), isLand = $t.hasClass('.land');

  function doSomething(){
    $t.width($anotherEl.width() + $anotherEl2.width());
    // other codes ...
  }
  doSomething();
  $(window).resize(doSomething);
});

function doSomething(par1, par2, par3, par4){
  var $t = par1 , $anotherEl = par2, $anotherEl2 = par3;
  $t.width($anotherEl.width() + $anotherEl2.width());
  // other codes ...
}

$('.elements').each(function(){
  // elements
  var $t = $(this), $anotherEl = $t.find('.el2'), $anotherEl2 = $t.find('.el3');

  // variables
  var isVisble = $t.is(':visible'), isLand = $t.hasClass('.land');

  doSomething($t, $anotherEl, $anotherEl2, isLand);
  $(window).resize(function(){
    doSomething($t, $anotherEl, $anotherEl2, isLand);
  });
});

感谢您的提前。

最佳答案

为什么要循环执行此操作?因为这可以在不使用循环的情况下完成,例如:

function doSomething(){
    $('.elements').each(function(){
         // elements
         var $t = $(this), $anotherEl = $t.find('.el2'), $anotherEl2 = $t.find('.el3');
         // variables
         var isVisble = $t.is(':visible'), isLand = $t.hasClass('.land');
         // now do something with the vars here.
    });
}

$(window).resize(doSomething).resize(); // <---trailing .resize() triggers on dom ready.
<小时/>

我发现您的方法存在的问题是:

  1. 使用.each()循环一次又一次地定义相同的函数,在每次迭代中执行相同的函数并绑定(bind)resize事件。
  2. 第二个似乎好一点,但部分原因是 .resize 绑定(bind)。

关于javascript - 在循环中定义函数的最佳方法是什么? - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35407783/

相关文章:

reactjs - React 调用动态状态名称

javascript - 使用 jquery 以相反(从下到上)方向追加输入框

javascript - 动态加载 Bootstrap 模态内容并使用 Angular.js 打开它

javascript - 如何在浏览器中将 DIV 调整为全屏

jquery - 使用 Kwicks 打开 Accordion slider 的第一行时遇到问题

multithreading - 即使没有 `hFlush stdout`,循环线程也会挂起而没有 `print`

java - Hangman Java 游戏打印错误和正确的猜测

javascript - 获取列表项中的文本 jquery 不适用于 chrome 和 ie

javascript - Electron - preload.js 未加载并且在 Windows 10 上发生错误

JavaScript 加密