0

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".
}
whostolemyhat
3,1194 gold badges36 silver badges50 bronze badges
asked Jan 30, 2013 at 9:47

2 Answers 2

2

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

answered Jan 30, 2013 at 9:59
Sign up to request clarification or add additional context in comments.

2 Comments

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 ?
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
1

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

answered Jan 30, 2013 at 10:01

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.