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.

More on this in JavaScript

There’s more to this in JavaScript than I showed last time. Time for more details on methods, closures and the global object.

This is a direct continuation of the this in JavaScript vs C# post. If you haven’t already read it, I suggest that you read it before continuing here.

More on Methods

Last time I finished with a code example with a method that allowed me to receive payments and show my current cash level. In this post I’ll add the same function as a method to another object.

this in JavaScript vs C#

Coming from C#/C++/Java, the usage of the this keyword in JavaScript is confusing. This is my attempt to explain it, in C# terms (with C# being very close to C++ and Java). I’ve thought of writing this post a long time, but it’s just now, when reading JavaScript: The Good Parts that I’ve finally understood it well enough myself to be able to explain it.

In C# (and C++ and Java) the this keyword is available inside any class method and refers to the current object used to invoke the method. When I first started writing JavaScript I assumed that it would be the same, but soon found out that I was wrong. this in JavaScript has a different behaviour.

JavaScript Objects

My first assumption was that inside a method the this keyword would refer to the current object. I was surprised when things didn’t behave as I expected, but it wasn’t this fault. It was my lack of understanding of JavaScript objects and methods. JavaScript is object oriented, but it is a prototypical object orientation which is not at all the same as the class-based object orientation in C#.

Software Development is a Job – Coding is a Passion

I'm Anders Abel, a systems architect and developer working for Kentor in Stockholm, Sweden.

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

The complete code for all posts is available on GitHub.

Popular Posts

Archives

Series

Powered by WordPress with the Passion for Coding theme.