0

The code below outputs

#document
#document

My expectation is that it outputs

#document
#head

Why is this not the case?

$(document).ready(function() {
    console.log(this);
    $("head").each((index, element) => {
        console.log(this);
    });
});

jQuery's own docs state:

More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element. (https://api.jquery.com/each/)

Possibly I'm missing some subtlety about the .call method (which is how jQuery invoked the anonymous function in the .each call) or closures. However, my understanding is that .call can be used to set the this parameter.

Andrew Parker
  • 1,425
  • 2
  • 20
  • 28
  • 3
    You're using an arrow function which [doesn't have it's own `this`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions) but uses the one from its outer lexical environment. That's why both outputs are `document`. – Andy Sep 01 '19 at 12:53
  • 2
    Was in the middle of typing the same as above. Here's a fiddle proving the point: https://jsfiddle.net/6x2uewrq/ – Rory McCrossan Sep 01 '19 at 12:55
  • Nice. Figured there'd be a simple answer. Thanks for the fast response. If you provide as an answer then I'll accept it. – Andrew Parker Sep 01 '19 at 12:55
  • And if I'd gone and looked at the arrow function docs then it's all there :) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Andrew Parker Sep 01 '19 at 12:57

0 Answers0