Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Introducing the Practice

The keyword 'this' behaves strangely when declared inside arrow function (ES6)

https://w.trhou.se/xbutg4gnu6 (see code in lines 25-27 in the workspace)

When I run the code below, it doesn't work locally unless I replace () => { with function() {. On the other hand this code works partially in Treehouse Workspace - it appliesstrike property, but it doesn't remove it on the second double click (meaning toggle doesn't work):

$('ul').on('dblclick', 'li', () => { $(this).toggleClass('strike'); });

1 Answer

Steven Parker
Steven Parker
231,008 Points

Arrow functions are not exact replacements for conventional functions. One difference is that they do not establish a value for "this".

For event handlers, you can usually use the "target" property of the passed-in event object as a substitute:

$('ul').on('dblclick', 'li', e => { $(e.target).toggleClass('strike'); });

For more details on arrow functions and how they are different from conventional functions, see this MDN page on Arrow function expressions.