/ / Proste informacje o źródle jquery, mylące w odniesieniu do słowa kluczowego „this” - javascript, jquery, this

Proste o źródle jquery, mylące o "tym" słowem kluczowym - javascript, jquery, this

Czułem się bardzo zdezorientowany co do „tego” słowa kluczowego w jquery 1.7.3 source.some fragmenty poniżej:

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".
}

Odpowiedzi:

2 dla odpowiedzi № 1

zwróć to zezwól na łańcuchowe wywołanie wtyczki,

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

jeśli nie return this we wtyczce nie będzie można go połączyć i łańcuch jest szybki, a łańcuch jest fajny chcesz połączyć jak najwięcej w swoim kodzie jquery

aby odpowiedzieć na twój komentarz: nie robisz (wewnątrz definicji wtyczki):

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

return this pochodzi na końcu definicji wtyczki nie ma potrzeby zwracania go pod żadnym warunkiem


1 dla odpowiedzi nr 2

tak, to jest obiektem jquery i zwraca to uczyń swoją funkcję łańcuchową.

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

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

Widzisz, metoda łączenia pomaga nam pisać kod szybciej i ładniej.

Jeśli chcesz dalej badać: http://en.wikipedia.org/wiki/Method_chaining