this and $(this) in jQuery callbacks

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:

// Handle $(DOMElement)
if ( selector.nodeType ) {
  this.context = this[0] = selector;
  this.length = 1;
  return this;
}

How jQuery Calls the Event Handler

When jQuery calls the event handler callback, it is done by using the apply() function and supplying the matched element as this.

ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
  .apply( matched.elem, args );

(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:

if ( selector.selector !== undefined ) {
  this.selector = selector.selector;
  this.context = selector.context;
}

The jQuery code snippets are taken from jQuery version 1.8.0

1 comment

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.