1

I've been confused on the difference between this and $(this). Looking into it, I found this succinct explanation which has worked for me for a while, but then I ran into the following in this tutorial:

$.fn.greenify = function() {
    this.css( "color", "green" );
    return this;
}

The tutorial explains: "Notice that to use .css(), another method, we use this, not $( this ). This is because our greenify function is a part of the same object as .css()"

Unfortunately, I don't entirely follow. I'm confused how you can use a JQuery method on a DOM object rather than on the JQuery wrapper for that DOM object. Any explanation anyone may have would be very helpful.

CLARIFICATION: my interest isn't so much the difference between this and $(this) -- I understand that the former belongs to JavaScript and (roughly speaking) refers to the global object, containing object, or calling DOm element, depending on circumstances, while the latter (again, generally speaking) refers to the JQuery-wrapped element being acted upon. I'm interested in why this.css() works in the above context.

The response I upvoted (apologies, I can't see the respondent's name from the edit screen) addressed that question pretty well, although I'm holding off on accepting that as the answer to gather more viewpoints.

Community
  • 1
  • 1
dcgenjin
  • 1,108
  • 3
  • 12
  • 25

2 Answers2

5

this within that scope of a jQuery plugin is the jQuery object collection, not a DOM node, and therefore has access to the jQuery methods.

However should you iterate over that jQuery object/collection, using each(), for example:

$.fn.greenify = function() {
    this.each(function(){
        this.css('color', 'green';
    });
    return this;
}

this is the DOM node of the element in the collection over which we iterate, and would therefore lead to a syntax error, and would require an explicit wrapping with jQuery to work:

$.fn.greenify = function() {
    this.each(function(){
        $(this).css('color', 'green';
    });
    return this;
}
David Thomas
  • 249,100
  • 51
  • 377
  • 410
3

Adding a function to $.fn is adding a function to the jQuery prototype object. (That's what $.fn is — the prototype object shared by every jQuery instance object.)

When you call a function like .greenify() from a some JavaScript code, then normal JavaScript function invocation rules come into play. As with a function on any other prototype object, the value of this inside the code for .greenify() or any other jQuery function will be the object referenced by the expression before the . operator. What sort of object is that in a statement like

$(".foo").greenify();

? It's a jQuery object!

Pointy
  • 405,095
  • 59
  • 585
  • 614