Cheerio: Arrow functions bug for .each() method

Created on 14 Jul 2017  路  4Comments  路  Source: cheeriojs/cheerio

Hi there,

It looks like there is some bug in processing arrow functions inside of a .each() iteration for a cheerio object.
E.g.
This will not work:
elements.each((i, element) => { console.log($(this).text()); });

Whereas, this works:
elements.each( function (i, element) { console.log($(this).text()); });

Anyone have any feedback on this? If this is a known issue I apologize, I'm relatively new to the cheerio community :)

Not a bug

Most helpful comment

@trevorfrese

Would element be a reference to this?

e.g.,

elements.each((i, element) => { console.log($(element).text()); });

All 4 comments

Hi there! The behavior you have reported is not directly related to Cheerio. Instead, it concerns the JavaScript language itself. Unlike "traditional" functions such as those defined with the function keyword, so-called "arrow functions" have a this value which is lexically-scoped. You can learn more about arrow functions at this page on the Mozilla Developer Network.

@jugglinmike is there a way to access the this value that Cheerio is using in the "traditional" function, while still using the "arrow function"?

@trevorfrese

Would element be a reference to this?

e.g.,

elements.each((i, element) => { console.log($(element).text()); });

@gforceg that works!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

AlbertoElias picture AlbertoElias  路  4Comments

M3kH picture M3kH  路  4Comments

rajkumarpb picture rajkumarpb  路  3Comments

tndev picture tndev  路  4Comments

gajus picture gajus  路  4Comments