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

Paul Brown
Paul Brown
7,057 Points

Fascinating. $(this) doesn't work as expected with arrow function.

I was going crazy trying to figure out what the problem was. When using arrow function, e.g.:

$(.work).on('sticky-start', () => {
  $(this).append('blahblahblah');
});

I tried logging THIS, and it shows as being Window in this case.

So in case anyone else runs into this, hopefully this'll help!

Yes I noticed it when I was learning jQuery Basics yesterday. You need to use the conventional 'function' style when constructing the function.

1 Answer

Paul Brown
Paul Brown
7,057 Points

Right, so in case this is somehow unclear, the way to correct this problem is change the arrow function into a normal anonymous function:

$(.work).on('sticky-start', function () {
  $(this).append('blahblahblah');
});

Now $(this) works.

This is because 'this' with arrow functions and lexical scoping. Here are 2 good resources of why you had that experience.

https://toddmotto.com/es6-arrow-functions-syntaxes-and-lexical-scoping/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions