As a jQuery neophyte I am somewhat confused by the different contexts in which the this keyword is used. Sometimes it refers to a DOM element e.g. this.id and sometimes it refers to a jQuery object e.g. $(this).val().
Remy Sharp’s blog post is helpful but I would like to know how you would explain the difference to a novice. Is the difference strictly a jQuery issue or common to all Javascript?
Thanks for all the responses so far – great stuff, I will pick an answer tomorrow. Here is another blog post I subsequently came across that was also helpful: What is this? by Mike Alsup.
Remy Sharp’s post is confusing if you don’t read it carefully, in my opinion. The meaning of
thisnever changes. In the example you gave, there were 2 uses ofthis. As a DOM element in an event:and wrapped as a jQuery object in an event:
If you read the 2 snippets above very carefully you’ll notice that
thisnever changes meaning. It always refers to the DOM element. The difference comes in how it is used.In jQuery, by default,
thisrefers to the DOM element (not a jQuery object) which triggered an event. In the second code snippet above, it is still the same DOM element, only it is wrapped in a jQuery element by wrapping$()around it. As with any argument to the jQuery constructor, passingthisinto the constructor transforms it into a jQuery object.I think the confusion comes in when Remy starts talking about jQuery plugins in the same article as jQuery events. jQuery plugins are something that people rarely write and frequently use. When writing a jQuery plugin, you’re working within the context of the jQuery object prototype. In this case, you’re using the word
thisto refer to the plugin you’re writing. In normal use-cases, you won’t be writing plugins often so this is a much less common scenario. When not in the scope of the plugin, you can’t usethisto refer to the jQuery object.In the JavaScript language, the keyword
thisrefers to the current instance of an object in JavaScript. When being used in a JavaScript prototype, it refers to the instance of the prototype. Depending on the browser, when using the non-jquery event model,thisalso refers to the DOM element. Because some browsers (Internet Explorer) don’t refer tothisas the DOM element in an event, it makes working with events difficult. To get around this, jQuery performs some JavaScript magic that always makesthisrefer to the DOM element which triggered the event. That is (one of the many) reasons to use a JavaScript framework instead of rolling your own.