简体   繁体   中英

What is the best way for defining functions in loops? - JavaScript

I want to know which way for defining functions in loops is better? I always use the first way. Is it correct? or there is another way for this case?

Please guide me, I use the first way a lot in my codes, I wonder if it is true?

$('.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);
});

or

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);
  });
});

Thanks for advance.

Why doing this in loops? As this can be done without using loops like:

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.

Problems i see with your approach are:

  1. Using .each() loop defining same function again and again, executing same function and binding resize event in each iteration.
  2. Second one seems a bit better but partially because of .resize bindings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM