jQuery源碼分析-建構函式詳解

來源:互聯網
上載者:User

標籤:io   ar   sp   for   java   on   div   bs   cti   

在jQuery.js的建構函式中,充分利用了JavsScript語言的動態性——對行參的類型和個數沒有的嚴格要求,以至於一個函數可以實現多種功能需求,也為JavaScript語言的多態性提供了基礎,在這個建構函式中,提供了六種不同的調用格式(根據官方API文檔),具體如下($ = jQuery):

  1、$(String expr):根據給定的CSS選擇符尋找匹配的元素,如$("div>p");
  2、$(Element elem):將給定的DOM元素對象轉換為jQuery對象,如$(document).find("div>p");
  3、$(Array<Element> elems):如$(myForm.elements).hide();
  4、$(Function fn):是$(document).ready()的簡寫入模式,如:$( function fn(){ ... } );
  5、$(jQuery obj):如:var div = $("div");   $(div).find("p");
  6、$(String expr, Element context):在context中尋找expr,如:$("div", xml.responseXML);

  另外,jQuery中提到了Chainable Methods的思想,也就是調用jQuery中的方法會返回一個jQuery對象,仍然可以繼續調用其中的方法,這樣,就形成了一個“鏈條”,通過“.”一個一個調用下去,這個在建構函式中有具體體現,其中有如下一條語句:

  if( window == this ) return new jQuery( a, c );

  這個就是為了返回一個jQuery對象,在首次調用jQuery( a, c )函數時,this是等於window的,所以每次都會建立一個jQuery對象,更詳細的程式碼分析見下:

                        // jQuery的建構函式;
var jQuery = function( a, c ) {
    // $(document).ready()的簡寫形式,只有在$(function(){ })下才會執行;
    if ( a && typeof a == "function" && jQuery.fn.ready ) return jQuery(document).ready(a);

    // 確保參數a非空,預設值為document;
     a = a || jQuery.context || document;

    // 如果參數a是jQuery對象(a.jquery="1.0.3"),則複製一個與a相同的jQuery對象;
    if ( a.jquery ) return jQuery( jQuery.merge( a, [] ) );

    // 從給定的參數c(要求c必須是jQuery對象)中尋找a;
    if ( c && c.jquery ) return jQuery( c ).find( a );

    // 如果是初次調用$(),因為在window環境下,所以建立一個新的jQuery對象,如果去掉new則迴圈執行;
    if ( window == this ) return new jQuery(a,c);

    // 分析HTML串,如“div<ul>p”;
    if ( a.constructor == String ) {
        var m = /^[^<]*(<.+>)[^>]*$/.exec( a );
        if ( m ) a = jQuery.clean( [ m[ 1 ] ] );
     }

    // 如果參數a是元素數組,則要執行jQery.merge(),否則要執行jQuery.find();
    this.get( a.constructor == Array || a.length && !a.nodeType && a[0] != undefined && a[0].nodeType
        ?  // 處理元素數組;
             jQuery.merge( a, [] )
         :  // 尋找相匹配的元素並儲存;
             jQuery.find( a, c ) );

    // 如果附加了另外的函數,則在每個相匹配的jQuery對象上執行這個函數;
    var fn = arguments[ arguments.length - 1 ];
    if ( fn && typeof fn == "function" ) this.each( fn );

    return this;

}; //jQuery的結束;

 

jQuery源碼分析-建構函式詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.