jQuery方法源碼解析--jQuery($)方法(一)

來源:互聯網
上載者:User

標籤:jquery

jQuery方法源碼解析--jQuery($)方法

註:
1.本文分析的代碼為jQuery.1.11.1版本,在官網上下載未壓縮版即可
2.轉載請註明出處

jQuery方法:
這個方法大家都不陌生,在使用過程中,它還有另外一個名字,貨幣符號:$,$(...)其實就是jQuery(...);它有很多種用法,通常都返回一個jquery對象,也可以作為$(document).ready(...);的簡寫形式,分析之前先看一下jQuery都有什麼用法。
1.jQuery( selector [, context ] )selector:String;context:Element or jQuery在context中返回一個符合selecttor運算式的jquery對象,context預設為$(document),如果找不到自然返回一個空的jquery對象,也就是length為0的jquery對象;
eg:$( "div.foo" ).click(function() {
  $( "span", this ).addClass( "bar" );
});
2.jQuery( element ),jQuery( elementArray )element :ElementelementArray : Array of Element將DOM元素或數組轉化(封裝)為一個jquery對象。PS:從實現的原理上來說,稱之為封裝更合適。
eg:$(document),$(this),$(document.getElementsByTagName("div"));
3.jQuery( object )object:PlainObject將一個普通對象轉為jQuery對象,普通對象:PlainObject,就是一個僅有鍵值對的對象;這有什麼用處?!暫時不大瞭解,官網給出解釋:At present, the only operations supported on plain JavaScript objects wrapped in jQuery are: 
.data(),.prop(),.on(), .off(), .trigger() and .triggerHandler(). 
The use of .data() (or any method requiring .data()) on a plain object will result in a new 
property on the object called jQuery{randomNumber} (eg. jQuery123456789).
4.jQuery( selection )selection :jQuery複製一個jQuery對象When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.
5.jQuery()返回一個空的jQuery對象
6.jQuery( html [, ownerDocument ] )html:htmlStringownerDocument:document建立一個新的dom元素,第二個參數指定建立元素所使用的document;當有多個iframe情境可能會用到第二個元素
eg:$( "<p id=‘test‘>My <em>new</em> text</p>" ).appendTo( "body" ); 
7.jQuery( html, attributes )html: htmlString,該情境下必須是單標籤attributes : PlainObject,一個使用鍵值對的形式描述元素屬性的對象eg:$( "<div></div>", {
     "class": "my-div",
     on: {
          touchstart: function( event ) {
          // Do something}
}}).appendTo( "body" );

如果第二個對象的屬性名稱字在jQuery中是一個函數(還可能是內建函式),會調用函數,屬性值會被當做參數。如果attributes過於複雜,個人不建議這麼寫,寫成下面這樣比較清晰。
$( "<div></div>" )
.addClass( "my-div" )
.on({
     touchstart: function( event ) {
     // Do something
     }
})
.appendTo( "body" );

8.jQuery( callback )callback:function沒什麼好說的,就是$(document).ready(callback)的簡寫形式。what is jQuery Object??
jQuery方法,通常返回的是一個jQuery對象,那麼,首先我們必須要知道jQuery對象到底是什麼,它大致長成什麼樣子.
在html寫幾個li:<body>
     <ol>
          <li></li>
          <li></li>
          <li></li>
          <li></li>
     </ol>
</body>
建立jQuery對象,並輸出出來:
console.log($("li"));
在chrome中運行如下:

可以看出來jQuery對象,具有類數組的結構,有著從0到length-1的索引和length屬性(但沒有數組的concat或者slice等其他方法),而每個li,就是element DOM對象.這個類數組的結構,可以看做是原生的js對象數組,除了這個類數組的結構外,其他的就是一些jQuery屬性和方法,開啟指向prototype的隱性指標,就可以看到很多我們常用的jQuery方法.
總結一下,jQuery對象,就是在js對象的基礎上,封裝了一些jQuery方法的對象,有一個英文詞形容的比較貼切,就是wrap(包裹).
jQuery方法的結構

在jQuery1.11.1的源碼中,搜尋jQuery,在源碼開始的不遠處,就可以看到如下的代碼:
// Define a local copy of jQuery
jQuery = function( selector, context ) {
      // The jQuery object is actually just the init constructor ‘enhanced‘
      // Need init if jQuery is called (just allow error to be thrown if not included)
      return new jQuery.fn.init( selector, context );
}
可以看到,jQuery就是一個函數,返回了一個對象.
== ,what?! 居然返回的是一個 jQuery.fn.init對象?!

我們搜一下jQuery.fn.init這貨:init = jQuery.fn.init = function( selector, context ) {
          var match, elem;          ......};
在這個函數結束之後,下面這個代碼撲面而來(不同版本這些代碼的位置不一定一樣,還是搜尋比較靠譜):// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;


再搜尋"jQuery.fn =",可以看到jQuery.fn = jQuery.prototype = {...};這回明了了,jQuery.fn就是jQuery這個函數的prototype,而init.prototype = jQuery.fn,就是說:
jQuery.fn.init.prototype = jQuery.prototype
那麼通過jQuery.fn.init.prototype的這個函數構造出來的對象,就可以通過指向jQuery.fn.init.prototype的引用,找到jQuery的prototype下的方法,從某種意義上來說,通過jQuery.fn.init構造出來的方法,就是jQuery對象了.
總結一下,jQuery對象的構造其實是通過jQuery.fn.init來實現的,通過init.prototype = jQuery.prototype,令jQuery.fn.init對象可以使用jQuery.prototype的方法屬性.jquery.init方法
在分析init方法之前,必須認識該方法用到的兩個Regex:第一個:// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/
從注釋上看也知道,這是匹配html的Regex,因為某個bug的原因,還要同時匹配#id形式的字串,進行優先處理.
/^(...)$/-->包裹著開始和結束定位器,匹配整個字串;(?:...) --> ?:表示這個分組不捕獲,僅僅是起分組的作用,可以提高效能;\s*(<[\w\W]+>[^>]*  -->匹配可以空白字元開頭,可以任意非‘>‘結尾的<tag>形式的字串#([\w-]*)  -->匹配以#開頭,跟著任意字母或減號的字串
整體翻譯過來,就是匹配<tag>或#id形式的字串
執行一下:rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/;
console.log(rquickExpr.exec("<tag>"));輸出:["<tag>", "<tag>", undefined, index: 0, input: "<tag>"]

另外一個正則:var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
看名字可以猜到,這是個匹配單標籤的形式。
<(\w+)\s*\/?> -->匹配一個標籤,可以使<tag>或<tag />的形式(?:<\/\1>|) -->\1表示分組1中捕獲的字串,也就是匹配和前面一樣的閉合標籤</tag>或者為空白字串(注意後面的或者符號什麼也沒跟,就是或者是Null 字元串)
合起來就是匹配<tag /> 或者是 <tag></tag>;不難發現,這個正則匹配不了<tag attr="..."></tag>這種帶屬性的單標籤,也匹配不了<tag>asdf</tag>這種帶文本節點的標籤,跟確切的說,這個正則只匹配單的空標籤.
jQuery方法可以說是JQ最核心的方法了,而它通過init方法實現,那麼它是不是很長呢?!還真不是,也就100行,因為它還調用了jQuery的其他方法,下面單就這個init方法結構,進行分析。
直接搜尋jQuery.fn.init,很快就能找到init函數的源碼,大致過一下,發現很多if else,這和jQuery這個函數功能的多樣性相符合;下面直接在代碼中寫注釋來解析這段代碼
init = jQuery.fn.init = function( selector, context ) {          var match, elem;          //處理jQuery()形式,返回空的jQuery對象          // HANDLE: $(""), $(null), $(undefined), $(false)          if ( !selector ) {               return this;          }          // Handle HTML strings          /*#源碼分析           *匹配html(以<開頭,以>結尾,或者是<tag>...形式,推薦寫嚴格的html),或者是#id形式,並且確保,#id情況下,沒有context           */          if ( typeof selector === "string" ) {               if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {                    /*#源碼分析                    *假設以<開頭,以>結尾的,並且長度大於3的String都是htmlString,然後存到match中                    */                    // Assume that strings that start and end with <> are HTML and skip the regex check                    match = [ null, selector, null ];               } else {                    match = rquickExpr.exec( selector );               }              /*#源碼分析               *what is match?               *我們分析過rquickExpr這個Regex,它有兩個分組(最外面的那個分組不捕獲,沒算),               *這樣使用exec方法後,如果匹配到了,則應該返回一個長度為3,包括index和input屬性的數組。               *那麼match[0]是整體匹配的數組,match[1]是匹配的<tag>標籤(如果有),match[2]匹配#id(如果有)               *顯然match[1],match[2]只能有一個被捕獲               */                                             // Match html or make sure no context is specified for #id               if ( match && (match[1] || !context) ) {                    //處理jQuery( html [, ownerDocument ] ),根據html產生dom元素,返回jQuery對象,就像下面的注釋$(html) -> $(array)                    //match[1]                    // HANDLE: $(html) -> $(array)                    if ( match[1] ) {                        /*#源碼分析                         *如果context是jQuery對象,轉為js原生對象.                         *我們說過,jQuery對象就是給js原生對象封裝了了一些方法的對象,而原生對象以類數組的形式存在jQuery中,                         *所以context[0],就是去jQuery對象中的第一個原生對象,在這裡context期待傳入的就是document或者$(document)                         */                         context = context instanceof jQuery ? context[0] : context;                        /*#源碼分析                         *這裡調用了jQuery.parseHTML方法,就是把htmlString轉為dom數組                         *還調用了jQuery.merge(first,second),接收兩個"類數組"參數,                         *這個方法是把第二個數組追加到第一個數組尾部,會改變第一個數組                         *前面講過,jQuery對象具有類數組結構,當前還沒有操作this,它的length = 0                         *所以下面這段代碼,就是把htmlString轉為dom數組並追加到this的尾部。                         */                         // scripts is true for back-compat                         // Intentionally let the error be thrown if parseHTML is not present                         jQuery.merge( this, jQuery.parseHTML(                              match[1],                              context && context.nodeType ? context.ownerDocument || context : document,                              true                         ) );                                                 /*#源碼分析                         *處理jQuery( html, attributes )這種用法                         *第一個參數必須是單標籤,第二個參數是一個普通對象,類似{html:"hello world",id:"test"}                         *注意,這種情況下,會走上面的分支,已經把單標籤轉為dom並拼接到了this中了                         */                         // HANDLE: $(html, props)                         if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {                              for ( match in context ) {                                  /*#源碼分析                                   *這裡的match是context的屬性                                   *如果有match的方法,就會調用match方法                                   *比如{html:"hello world",id:"test"},就會調用this.html("hello world")方法                                   *否則按照屬性處理                                   */                                   // Properties of context are called as methods if possible                                   if ( jQuery.isFunction( this[ match ] ) ) {                                        this[ match ]( context[ match ] );                                   // ...and otherwise set as attributes                                   } else {                                        this.attr( match, context[ match ] );                                   }                              }                         }                         return this;                   /*#源碼分析                    *處理match[2]被捕獲到的情況,也就是#id的情況                    */                    // HANDLE: $(#id)                    } else {                         elem = document.getElementById( match[2] );                         // Check parentNode to catch when Blackberry 4.6 returns                         // nodes that are no longer in the document #6963                         // 為了相容Blackberry 4.6中的一個bug,不但判斷element,還要判斷elem.parentNode                         if ( elem && elem.parentNode ) {                              // Handle the case where IE and Opera return items                              // by name instead of ID                             /*#源碼分析                              *早期的IE的document.getElementById()有bug,在尋找元素時,會把表單的元素的name也看成是id,                              *這時候使用find方法來相容,搜尋一下"rootjQuery =",會發現rootjQuery = jQuery( document );                              */                              if ( elem.id !== match[2] ) {                                   return rootjQuery.find( selector );                              }                             /*#源碼分析                              *否則直接放到this[0]中                              */                              // Otherwise, we inject the element directly into the jQuery object                              this.length = 1;                              this[0] = elem;                         }                         this.context = document;                         this.selector = selector;                         return this;                    }              /*#源碼分析               *處理$(複雜選取器的情況),採用find方法處理並返回,               *這裡兩個else的判斷,就是為了確保是jQuery對象調用find方法,               *如果context不是jQuery對象,使用constructor構造一個               *context.jquery-->jquery是jQuery.fn上的一個版本屬性,在此用這個來判斷是否是jQuery對象。               */               // HANDLE: $(expr, $(...))               } else if ( !context || context.jquery ) {                    return ( context || rootjQuery ).find( selector );               // HANDLE: $(expr, context)               // (which is just equivalent to: $(context).find(expr)               } else {                    return this.constructor( context ).find( selector );               }         /*#源碼分析          *else selector不是String類型的          */          // HANDLE: $(DOMElement)          } else if ( selector.nodeType ) {              /*#源碼分析               *處理$(DOMElement)形式,這個比較簡單,就是加到this[0]上               */               this.context = this[0] = selector;               this.length = 1;               return this;          // HANDLE: $(function)          // Shortcut for document ready          } else if ( jQuery.isFunction( selector ) ) {              /*#源碼分析               *$(function)形式,就是調用了$(document).ready()方法               */               return typeof rootjQuery.ready !== "undefined" ?                    rootjQuery.ready( selector ) :                    // Execute immediately if ready is not present                    selector( jQuery );          }         /*#源碼分析          *如果selector.selector !== undefined,那麼selector本身可能就是一個jQuery對象,做了如下處理,為什麼呢?!不知道          */          if ( selector.selector !== undefined ) {               this.selector = selector.selector;               this.context = selector.context;          }         /*#源碼分析          *jQuery.makeArray(arr)是把類數組,轉為純數組形式,API是這麼說的.          *實際上makeArray還有第二個參數,但僅限內部使用,就是現在這種情況          *jQuery.makeArray( arr, results ) -->把調用jQuery.merge把arr數組追加到results尾部          *這裡會處理jQuery( elementArray )、jQuery( object )這兩種情況          */          return jQuery.makeArray( selector, this );};


下集預告經過分析之後大概對jQuery這個函數有了大致的瞭解,這個函數還調用了其他的jQuery的工具函數:比如jQuery.merge、 jQuery.parseHTML、jQuery.isPlainObject、find、$(document).ready()、jQuery.makeArray方法下一篇文章對以上的方法中選幾個簡單的進行分析,太複雜的,先放一放吧。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.