0

以下に示すjquery1.7.3source.someスニペットの「this」キーワードについて非常に混乱しました。

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

2 に答える 2

2

これを返すと、連鎖可能なプラグイン呼び出しが可能になります。

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

プラグインを使用しない場合return this、プラグインをチェーンすることはできません。チェーンは高速で、チェーンはクールです。jqueryコードで可能な限りチェーンする必要があります。

あなたのコメントに答えるために:あなたはしません(プラグイン定義内):

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

return thisプラグイン定義の最後に来るので、どんな条件でもそれを返す必要はありません

于 2013-01-30T09:59:25.067 に答える
1

はい、これはjqueryオブジェクトであり、これを返すと関数が連鎖可能になります。

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

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

おわかりのように、連鎖法は、コードをより速く、よりきれいに書くのに役立ちます。

さらに調査したい場合: http://en.wikipedia.org/wiki/Method_chaining

于 2013-01-30T10:01:59.453 に答える