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 One Solution

Gerald Bishop
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Gerald Bishop
Python Development Techdegree Graduate 16,897 Points

Should arrow functions work with the "this" keyword in jQuery?

The code on lines 25 to 27 of app.js do not seem to work with the this keyword:

https://w.trhou.se/dn6vvff3ll

I can only get it to work if I change the ()=> arrow function to a function declaration, i.e., using the function keyword or by changing the this keyword to event.target and inserting event as a parameter.

Can I change my code to get the arrow function to work with the this keyword?

Thanks

josephweiss2
josephweiss2
6,982 Points

the link doesn't work, can you Passover your code? that will make it better to see what's the problem. Thanks

Gerald Bishop
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Gerald Bishop
Python Development Techdegree Graduate 16,897 Points

josephweiss2 sorry I accidentally deleted the snapshot. Here is the code that doesn't work:

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

As Steven says, the ()=> needs to be changed to function() for it to work with the this keyword.

Steven Parker
Steven Parker
229,644 Points

This is a better solution than converting the function so you can use "this":

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

1 Answer

Steven Parker
Steven Parker
229,644 Points

This is not related to jQuery. Arrow functions just don't bind "this" like conventional functions do. For more details, see this MDN page on Arrow function expressions.

But for event handlers, passing the event object to a parameter is the "best practice" approach anyway.