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 trialBjörn Norén
9,569 PointsA question about "this"
Hi, I just wonder what "this" is in this situation. I tried to prompt it and got [object Object].
Is it pointing to the a-tag in the menu-id? I ask cause I feel it's time for me grasp the concept of this and understand its functions ... Thanks!
var $select = $("<select></select>");
$("#menu").append($select);
$("#menu a").each(function(){
var $anchor = $(this);
var $option = $("<option></option>");
$option.val($anchor.attr("href"));
$option.text($anchor.text());
$select.append($option);
var message = prompt($anchor);
});
2 Answers
Daniel Gonzalez
22,105 PointsHi,
Below is a great TeamTreehouse workshop about the use of "this" in javascript.
https://teamtreehouse.com/library/understanding-this-in-javascript
Angelica Hart Lindh
19,465 PointsHi Björn,
Daniel pointed out a great workshop from Treehouse on 'this' in JavaScript.
I wanted to explain 'this' in your context also, perhaps it will help. The keyword $(this)
within the $("#menu a").each(function(){});
relates to the current subject being passed to the iterator, in this case it is a DOM element <a></a>
tag.
The reason you are having [object Object]
returned in your prompt is because the jQuery $(this)
returns the DOM element as a jQuery object so to reference it in your prompt you would do:
var message = prompt($anchor[0]);
However, jQuery is used to help with DOM manipulation and you don't necessarily need to use the jQuery $(this)
. For example:
$(this)[0] === this;
So in your code
prompt($(this)[0])
// Same as
prompt(this);