3

Could someone please explain a bit, what difference between them?

For example I could do that with "that":

var bar;
button.click(function () {
    if (bar == this) {
        alert('same');
    }
    bar = this;
});

and couldn't with $(that):

var bar;
button.click(function(){
  if(bar == $(this)) {alert('same');}
  bar = $(this);
});
Somebody
  • 9,316
  • 26
  • 94
  • 142

4 Answers4

7

this is the plain Javascript object.

$(this) is a jQuery wrapped element. You are allowed to call jQuery methods with it.

deceze
  • 510,633
  • 85
  • 743
  • 889
kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
7

Your second example doesnt work, because every time you use the $(this) function, it returns an unique jQuery Object:

var a = document.createElement('a');
var b = $(a);
var c = $(a);

Now, b and c are both unique jQuery instances.

console.log(c == b) // prints false

When using jQuery click events, this is the event.currentTarget in the callback, which is the HTML element that bound the click:

button.click(function(e) {
    console.log (e.currentTarget == this) // prints true
})

$(this) or jQuery(this) is a function that returns the HTML element wrapped in a unique jQuery Object, and contains all jQuery prototypes.

David Hellsing
  • 106,495
  • 44
  • 176
  • 212
1

$(this) creates a jQuery object containing this. this is the HTMLElement representing the button which was clicked.

strager
  • 88,763
  • 26
  • 134
  • 176
1

Here's quite a good page that explains it in detail with examples.

(Note: It was also the first google result for "jquery this")

Blair McMillan
  • 5,299
  • 2
  • 25
  • 45