I often see examples of using the keyword this
in jquery. Sometimes I see it used with the $ and parenthesis, other times without. And I thought I saw it used with a little of each.
So,
var id = this.attr('id');
var id = $(this).attr('id');
var id = $this.attr('id');
Are these all the same? Is there a preferred way? Is this
a javascript thing and $(this)
a jQuery thing? If so, where does $this
fall?
I know this is probably a total newbie question, but I haven't been able to get the simple, this
, by itself, to work. I can only get $(this)
to work. I'm not sure if I'm doing something wrong, or if I've been reading examples with typos.
this
is a JavaScript thing. It refers to the "context" a function is running in. For most event handlers, it is the ("raw") DOM element that is listening to an event. In other situations it will mean other things; Googling "this
in JavaScript" might be enlightening.
I say it is the "raw" DOM element because jQuery is often used to wrap plain DOM elements in a jQuery wrapper, so you can use jQuery methods like attr
instead of the usual ones (getAttribute
, setAttribute
, etc.). This wrapping is accomplished with the $
function, and that's where you see $(this)
. For example:
this.getAttribute("href")
/* or */ someElement.getAttribute("href")
is the same as
$(this).attr("href")
/* or */ $(someElement).attr("href")
$this
or this$
is just a variable name. But, it is often conventional to do an assignment like
var $this = $(this);
The reason for this is to avoid continually invoking the $
function, which is somewhat expensive as it creates a new jQuery wrapper object every time. If you store the wrapped element in a variable, you gain slightly in efficiency.
In rare cases, this
might already be a jQuery wrapper. The case that comes up often for me is when writing jQuery plugins. In that case you can do things like this.attr("id")
directly, without wrapping it up first, because it's already wrapped. In the usual cases (event handlers, $.each
, etc.) the wrapper is necessary.
'this' is a Javascript object keyword for referring to the current object, '$(this)' is the jQuery wrapper function that turns the current object into a jQuery object, and when you see '$this' it usually refers to a variable that the developer created to refer to the $(this) object, it's useful during a $.each loop. For example:
$(function(){
$('a').click(function(){
var $this = $(this); // refers to the $('a') object
$('div').each(function(){
$(this).hide(); // $(this) refers to each 'div' in the loop, not the $('a')
$this.css({ color: 'blue' }); // turns the link element text blue
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With