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

  • Pingback: Client-side Development with jQuery on 2019-05-15
  • Leave a Reply

    Your name as it will be displayed on the posted comment.
    Your e-mail address will not be published. It is only used if I want to get in touch during comment moderation.
    Your name will be a link to this address.
Software Development is a Job – Coding is a Passion

I'm Anders Abel, an independent systems architect and developer in Stockholm, Sweden.

profile for Anders Abel at Stack Overflow, Q&A for professional and enthusiast programmers

Code for most posts is available on my GitHub account.

Popular Posts

Archives

Series

Powered by WordPress with the Passion for Coding theme.