Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,822 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,822 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]"