0

This tripped me up for a while. I had assumed they were the exact same thing. When using the function () syntax with jQuery .each(), this would refer to the current element, as per the documentation. When I wrote it using lambda syntax this seemed to refer to the entire Window. To be safe I used the (index, element) callback to make sure I'm always working with the element, but I'm still unclear as to why it behaves differently depending on syntax. See example.

function test() {
  $(".foo").each(function () {
    console.log($(this).text());
  });
  
  $(".bar").each(() => 
    console.log($(this).text())
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foo">Foo</div>
<div class="bar">Bar</div>
<button onclick="test()">Test</button>
Valuator
  • 3,262
  • 2
  • 29
  • 53

0 Answers0