tags:

views:

82

answers:

4

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);
});
+7  A: 

this is the plain Javascript object.

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

kgiannakakis
doesn't really answer the question...
David
Wow! Fast responces.Thanks, got it now. :)
Beck
+1  A: 

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

strager
+1  A: 

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

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