50

I have this ES6 code, after I compile it with Babel to ES5 the this inside .each's call back becomes undefined. How do I fix this problem?

let mediaBoxes = $(".now-thumbnail");
let titles = [];
mediaBoxes.each(() => {
      let obj = {
              index: i,
              title: $(this).find(".now-thumbnail-bottomtext").text().trim()
           };
  titles.push(obj);
});
Tushar
  • 85,780
  • 21
  • 159
  • 179
Tekeste Kidanu
  • 1,950
  • 2
  • 14
  • 22

2 Answers2

78

My solution is to not use this at all, but use the variables that are passed to the callback function. The first one is the index and the second one gives you the DOM element itself.

let mediaBoxes = $('.now-thumbnail');
let titles = [];
mediaBoxes.each((index, element) => {
  let obj = {
    index: index,
    title: $(element).find('.now-thumbnail-bottomtext').text().trim(),
  };
  titles.push(obj);
});
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
Tekeste Kidanu
  • 1,950
  • 2
  • 14
  • 22
42

That is because the mean of this is not the same in arrow functions.

this

Arrow functions capture the this value of the enclosing context,

The each() function passes the element as the second argument to the callback.

But a more appropriate solution for you will be to also use .map() instead of each()

let mediaBoxes = $(".now-thumbnail");
let titles = mediaBoxes.map((i, el) => {
  return {
    index: i,
    title: $(el).find(".now-thumbnail-bottomtext").text().trim()
  };
}).get();
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • I was thinking the same. `let titles = $('.now-thumbnail').map((index, element) => ({ index: index, title: $(element).find(".now-thumbnail-bottomtext").text().trim() })).get();` – Tushar Apr 15 '16 at 04:05
  • @Tushar if the content is too big then I like to break it into a block – Arun P Johny Apr 15 '16 at 04:59
  • 2
    I'd also add that _there is no need of arrow functions here just for concise syntax and nothing is being returned. Anonymous functions can be used where `$(this)` will point to correct element_. – Tushar Apr 15 '16 at 05:02
  • @Tushar I'd upvote that answer in a heartbeat. I see absolutely no benefit to an arrow here. Even if terseness is the goal, writing `function()` is exactly the same number of characters as `(i, el) =>` – CodingIntrigue Apr 15 '16 at 07:23