1

My app.js is written in es6 standard and my question is > How can I use code like this?:

$('img').each(() => {
    var title = $(this).attr('src');
    titles.push(title);
});

I observed that node compile this code to:

'use strict';

$('img').each(function () {
    var title = $(undefined).attr('src');
    titles.push(title);
});

compile 'this' to 'undefined', how can I fix that? thx in advance ;)

DAXaholic
  • 33,312
  • 6
  • 76
  • 74
Alexander Barac
  • 125
  • 1
  • 1
  • 5
  • 1
    Please read [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](http://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch) – Felix Kling Mar 26 '16 at 16:03

2 Answers2

1

Arrow functions bind the this value lexically - see MDN docu

Since this is already bound lexically, invoking an arrow function through the call() or apply() methods can only pass in arguments, but has no effect on this:

You can fix it by simply using a plain old function :)

DAXaholic
  • 33,312
  • 6
  • 76
  • 74
1

Another solution is to use the element passed to the callback, as defined in the .each documentation - Function ( Integer index, Element element ):

var titles = [];

$('img').each((index, element) => {
    var title = $(element).attr('src');
    titles.push(title);
});

document.getElementById('demo').innerHTML = JSON.stringify(titles, undefined, 4);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img src="http://38.media.tumblr.com/avatar_502c67b98956_64.png">

<img src="https://s-media-cache-ak0.pinimg.com/favicons/62c7e8f531e824f6f8da34453cdd698a8856f3aea36118408c3e5c09.png?9e884f0299eee37aedab60fe1ed363b5">

<pre id="demo"></pre>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209