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 AJAX Basics (retiring) AJAX and APIs Adding jQuery

Michael Pashkov
Michael Pashkov
22,024 Points

Can we use arrow functions?

Like $(document).ready(() => { $('button').click(() => { $(this).addClass("selected");
}); }); //end ready

instead of

$(document).ready(function () { $('button').click(function () { $(this).addClass("selected");
}); }); //end ready

Dave StSomeWhere
Dave StSomeWhere
19,870 Points

What happened when you tried it out?

Michael Pashkov
Michael Pashkov
22,024 Points

:) Interesting question, Dave. Why couldn't we use arrow function?

1 Answer

Dave StSomeWhere
Dave StSomeWhere
19,870 Points

Testing it out and checking the documentation is the best way to figure it out.

The key issue as stated in the MDN Arrow Function Doc

An arrow function does not have its own this; the this value of the enclosing lexical context is used i.e. Arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope they end up finding this from its enclosing scope . Thus, in the following code, the this within the function that is passed to setInterval has the same value as this in the lexically enclosing function:

So, if you test it out (check out this test pen

And you see the following in the console (also the class will only be added in the regular function):

"regular this is [object HTMLButtonElement]"

"arrow this is [object Window]"