Take the 2-minute tour ×

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".
share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

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

share|improve this answer
If I don't use jquery in my project,I want to check if an element have an ID call "div1",I general write like this:if(!document.getElementById('div1')) return;.in this case,should I write if(!document.getElementById('div1')) return this ? –  Ryan Yiada Jan 30 '13 at 10:05
no return this actually comes at the end of plugin definition whatever happens before; in your example in fact return this should come only once - see answer edit –  mikakun Jan 30 '13 at 10:10
add comment

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

// chaining
   .css('margin-left', '11px');

// no chaining
$('#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

share|improve this answer
add comment

Your Answer


