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 trialPaul Brown
7,057 PointsFascinating. $(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!
1 Answer
Paul Brown
7,057 PointsRight, 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.
Alexander La Bianca
15,959 PointsThis 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
Osaro Igbinovia
Full Stack JavaScript Techdegree Student 15,928 PointsOsaro Igbinovia
Full Stack JavaScript Techdegree Student 15,928 PointsYes I noticed it when I was learning jQuery Basics yesterday. You need to use the conventional 'function' style when constructing the function.