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 trialJoshua Kaufman
19,193 PointsArrow Function Syntax doesn't seem to correspond with the "this" element. Why is this?
This Jquery Works fine:
//Task: Prevent spoilerphobes from seeing spoilers //Solution: Hide spoilers and reveal them through user interaction
//1. Hide spoiler
$(".spoiler span").hide();
//2. Add a button
$(".spoiler").append("<button>Reveal Spoiler!</button>");
//3. When button Pressed
$("button").click(function() {
//3.1 Show spoiler
$(this).prev().show();
//3.2 Get rid of button
$(this).hide();
});
But this Jquery does NOT:
//Task: Prevent spoilerphobes from seeing spoilers //Solution: Hide spoilers and reveal them through user interaction
//1. Hide spoiler
$(".spoiler span").hide();
//2. Add a button
$(".spoiler").append("<button>Reveal Spoiler!</button>");
//3. When button Pressed
$("button").click(() => {
//3.1 Show spoiler
$(this).prev().show();
//3.2 Get rid of button
$(this).hide();
});
The second one doesn't really read the command "this", which is weird because I thought "function(){}" === "() => {}" in terms of logic, but evidently it's not the case. Is this a common issue?
1 Answer
Steven Parker
231,269 PointsThat's an intentional part of the arrow function design.
There are programming patterns where the binding of this
can be more of an annoyance that a benefit, and this is one of several intentional differences between conventional functions and "arrow" functions. For a complete discussion of the differences, see this Arrow Functions documentation page.
But you can still use them for event handlers, just be sure to pass in the event object, and use its target property instead of this.
Also, to keep your posted code readable, always use the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area.