Ryan Yiada
Ryan Yiada

Reputation: 4769

Simple about jquery source,confusing about "this" keyword

I felt very confused about "this" keyword in jquery 1.7.3 source.some snippets showing below:

jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
    var match, elem, ret, doc;

    // Handle $(""), $(null), or $(undefined)
    if ( !selector ) {
        return this;   
    }

    // Handle $(DOMElement)
    if ( selector.nodeType ) {
        this.context = this[0] = selector;
        this.length = 1;
        return this;
    }

if ( !selector ) {

  return this;   //why not only one "return" here?
                 //And does "this" refer to jQuery object?
                 //OTOH, this question is about why it returns "this".
}

Upvotes: 0

Views: 78

Answers (2)

mikakun
mikakun

Reputation: 2265

return this allow for chainable plugin call,

$(whatever).plugin1().plugin2() etc

if you don't return this in a plugin you won't be able to chain it & chaining is fast, & chaining is cool you want to chain as much as possible in your jquery code

to answer your comment : no you do (inside plugin definition):

if ($("#div1").get(0)) {
   //do whatever to $("#div1")
   }
return this;

return this comes at the end of plugin definition no need to return it upon any condition whatsoever

Upvotes: 2

phnkha
phnkha

Reputation: 7892

yes, this is jquery object and return this make your function chainable.

// chaining
$("#person").slideDown('slow')
   .addClass('grouped')
   .css('margin-left', '11px');

// no chaining
$('#person').slideDown('slow');
$('#person').addClass('grouped');
$('#person').css('margin-left', '11px');

You see, chaining method help us write code faster and prettier.

In case you want to research further: http://en.wikipedia.org/wiki/Method_chaining

Upvotes: 1

Related Questions