Remy Sharp's post is nothing but more confusing in my opinion. The meaning of this
never changes. In the example you gave, there were 2 uses of this
. As a DOM element in an event:
$('a').click(function() {
alert(this.tagName);
});
and as a jQuery object in an event:
$('a').click(function() {
alert($(this).val());
});
If you read the 2 snippets above very carefully you'll notice that this
never changes meaning. It always refers to the DOM element. The difference comes in how it is used.
The most basic way to treat this
is as the DOM element 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, passing this
into 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 this
to 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 use this
to refer to the jQuery object.
In the JavaScript language, the keyword this
refers 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, this
also refers to the DOM element. Because some browsers (Internet Explorer) don't refer to this
as the DOM element in an event, it makes working with events difficult. To get around this, jQuery performs some JavaScript magic that always makes this
refer 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.