What’s this and $(this) in jQuery callbacks? I’ve used them extensively, but never really paid attention to them until after I wrote the posts on what this is in JavaScript (part1 and part2). Now that I know how this works in JavaScript I got curious on how this is handled in jQuery and how $(this) is bound to the current element in jQuery event handler callbacks. The findings were not surprising, but rather show that jQuery is a well designed library.

Summary

The findings are simple:

this is a reference to the html DOM element that is the source of the event.

$(this) is a jQuery wrapper around that element that enables usage of jQuery methods.

jQuery calls the callback using apply() to bind this.

Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.

Let’s a have a look at how jQuery handles those cases internally.

jQuery $(this)

Calling $(this) ends up in the part of the jQuery constructor that takes care of a supplied DOMElement:

(Don’t ask me about the first line. It tries a few different ways of getting hold of the function to call, but I haven’t dug into the details so I have no idea of why).

Handling $($(this))

The last thing I looked at was how jQuery handles the common mistake where $(selector) is called on a variable that is already the result of another call to $(selector). At the end of jQuery.fn.init function there is a block handling this special case: