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.
thisis 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 “thisin 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
attrinstead of the usual ones (getAttribute,setAttribute, etc.). This wrapping is accomplished with the$function, and that’s where you see$(this). For example:is the same as
$thisorthis$is just a variable name. But, it is often conventional to do an assignment likeThe 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,
thismight 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 likethis.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.