詳解jQuery的$符號和init函數


本文所有代碼,出自jQuery.1.5.2,為方便理解,引入類的概念,雖然jQuery不是基於面向對象思想。

jQuery是現在最流行的JavaScript框架, $是其中最常見的符號,已經在jQuery留下了深深的烙印。
那么$到底是什么東西,它可以接受一個字符,也可以接受一個文檔對象,亦或者一個函數,也可以調用一個函數。
接下來我會徹底分析這個符號背后隱藏的秘密。

jQuery,高效,精煉,特別是對DOM元素對象操作的簡化,很大程度上將前端程序員從一大堆冗余的代碼解放出來,大大提高了開發效率!對多瀏覽器的兼容性,也最大限度讓程序員擺脫各種bug的糾纏

 

$符號作為元素選擇器的簡寫,最早是由Prototype庫使用,來簡寫getElementById,jQuery沿襲這一理念,並發揚光大,使$符號成為了jQuery最別具一格的特點。那么在jQuery中,$符號到底是啥?

熟悉jQuery的人應該知道,幾乎jQuery所有操作,都是從$符號開始,當作為元素選擇器的時候,操作結果返回的是一個jQuery對象。
那么,現在就看jQuery類的構造函數的主要代碼

jQuery對象的構造函數

[javascript]  view plain  copy
 
 print?
  1. var jQuery = (function() {  
  2.     //創建jQuery對象,給所有的jQuery方法提供統一的入口,避免繁瑣難記  
  3.     var jQuery = function( selector, context ) {  
  4.         //jQuery的構造對象,調用了jQuery.fn.init方法  
  5.         //最后返回jQuery.fn.init的對象  
  6.         return new jQuery.fn.init( selector, context, rootjQuery );  
  7.     },  
  8.   
  9.     .....  
  10.   
  11.     //定義jQuery的原型,jQuery.fn指向jQuery.prototype對象  
  12.     jQuery.fn = jQuery.prototype = {  
  13.     //重新指定構造函數屬性,因為默認指向jQuery.fn.init  
  14.     constructor: jQuery,  
  15.     init: function( selector, context, rootjQuery ) {.....},  
  16.   
  17.     ......  
  18.   
  19.     }  
  20.   
  21.     ......  
  22.   
  23.     //返回jQuery變量,同時定義將全局變量window.jQuery和window.$指向jQuery  
  24.     return (window.jQuery = window.$ = jQuery);  
  25.   
  26. })();  

從以上jQuery的主體結構,我們可以看出,當首次執行完畢后,全局變量$和jQuery,都是指向了var jQuery=function(selector,context){}這個函數,這里,就可以下個結論,$就是jQuery的別名,實際調用jQuery.fn.init

再看看var jQuery=function(selector,context){}這個構造函數,為什么里面不直接返回jQuery的對象?而是調用另外一個方法呢?

假如直接返回對象的話,每次使用jQuery對象,都要new jQuery() 這樣的話,十分不方便,直接將new 這個操作封裝在jQuery構造函數里面,簡化了實例化的操作,同時,jQuery通過了jQuery或者$符號,統一了接口,方便代碼的編寫,化繁為簡,提高效率。

那么jQuery類具體是如何構造的?居然能支持各種參數形式的調用
直接上jQuery.fn.init的“轅馬”,jQuery的真實構造器,我們就可以完全清楚了

[javascript]  view plain  copy
 
 print?
  1. /*所有查找或生成元素的結果,封裝為jQuery對象數組返回. 
  2.     */  
  3.     init: function( selector, context, rootjQuery ) {  
  4.         var match, elem, ret, doc;  
  5.   
  6.         // 1)處理 $(""), $(null), or $(undefined)  
  7.         //this指向jQuery對象  
  8.         if ( !selector ) {  
  9.             return this;  
  10.         }  
  11.   
  12.         // 2)處理 $(DOMElement)  
  13.         //selector.nodeType得知為DOM元素,如果是DOM元素直接放進jQuery對象數組中  
  14.         if ( selector.nodeType ) {  
  15.             this.context = this[0] = selector;  
  16.             this.length = 1;  
  17.             return this;  
  18.         }  
  19.   
  20.         //3)body元素只出現一次, 優化查找  
  21.         if ( selector === "body" && !context && document.body ) {  
  22.             this.context = document;  
  23.             this[0] = document.body;  
  24.             this.selector = "body";  
  25.             this.length = 1;  
  26.             return this;  
  27.         }  
  28.   
  29.         //4)如果是字符串,有六種情況,  
  30.         /* 
  31.         *(1)單個html元素 不帶屬性對象字面量 :createElement + merge 
  32.         *(2)單個html元素 帶屬性對象字面量 :createElement + attr + merge 
  33.         *(3)多個html元素  :buildFragment + merge 
  34.         *(4)#id 不帶context   :getElementById或者getElementById + Sizzle 
  35.         *(5)#id 帶context :Sizzle 
  36.         *(6)experession string :Sizzle 
  37.         *(7)標簽選擇器 :Sizzle(內置getElementByTagName) 
  38.         */  
  39.         if ( typeof selector === "string" ) {  
  40.             // 判斷是否為HTML string 還是 ID  
  41.             //如果是HTML strings  match[1] 非空  
  42.             //如果是ID strings match[1] 空  
  43.             //quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,  
  44.             match = quickExpr.exec( selector );  
  45.   
  46.             // 分析匹配結果,且當#id沒有context參數,例如不是$('#xxx',xxx)  
  47.             if ( match && (match[1] || !context) ) {  
  48.   
  49.                 // 處理HTML字符 $(html) -> $(array)  
  50.                 if ( match[1] ) {  
  51.                     //如果context為jQuery對象,則取用第一個元素,即是context[0]  
  52.                     context = context instanceof jQuery ? context[0] : context;  
  53.                     //取得document文檔  
  54.                     doc = (context ? context.ownerDocument || context : document);  
  55.   
  56.                     //判斷是否為單個元素字符串  
  57.                     ret = rsingleTag.exec( selector );  
  58.                     //單個元素  
  59.                     if ( ret ) {  
  60.                         //帶對象屬性字面量  
  61.                         //檢查context是否為對象字面量,適用場景  
  62.                         //例如$('<div>', { 'id': 'test', 'class': 'test' });  
  63.                         if ( jQuery.isPlainObject( context ) ) {  
  64.                             selector = [ document.createElement( ret[1] ) ];  
  65.                             jQuery.fn.attr.call( selector, context, true );  
  66.   
  67.                         } else {  
  68.                         //不帶對象字面量  
  69.                         //例如$('<div>')  
  70.                             selector = [ doc.createElement( ret[1] ) ];  
  71.                         }  
  72.   
  73.                     } else {  
  74.                         //如果是多個元素字符串,例如$('<div><a></a></div>')  
  75.                         ret = jQuery.buildFragment( [ match[1] ], [ doc ] );  
  76.                         selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;  
  77.                     }  
  78.                     //將生成結果selector 合並到jQuery對象中  
  79.                     return jQuery.merge( this, selector );  
  80.   
  81.                 // 處理$("#id"),例如$("#xxx");  
  82.                 } else {  
  83.                     elem = document.getElementById( match[2] );  
  84.   
  85.                     if ( elem && elem.parentNode ) {  
  86.                         //處理IE和Opera ID 與 Name 混淆的bug,使用Sizzle查找  
  87.                         if ( elem.id !== match[2] ) {  
  88.                             return rootjQuery.find( selector );  
  89.                         }  
  90.   
  91.                         // 否則,簡單插入jQuery對象數組  
  92.                         this.length = 1;  
  93.                         this[0] = elem;  
  94.                     }  
  95.   
  96.                     this.context = document;  
  97.                     this.selector = selector;  
  98.                     return this;  
  99.                 }  
  100.   
  101.             // 處理 $(expr, $(...)),使用Sizzle查找,例如$("div"),$('div > a'),$('div,a'),$('div:first')  
  102.             } else if ( !context || context.jquery ) {  
  103.                 return (context || rootjQuery).find( selector );  
  104.   
  105.             // 處理: $(expr, context),例如$('div a');或者$('a','div')或者$('div').find('a');  
  106.             } else {  
  107.                 return this.constructor( context ).find( selector );  
  108.             }  
  109.   
  110.         //5)處理: $(function),設置DOM載的時候綁定的函數,等同於$().ready(){foo}  
  111.         } else if ( jQuery.isFunction( selector ) ) {  
  112.             return rootjQuery.ready( selector );  
  113.         }  
  114.         //6)處理:$($(...)),完成克隆jQuery對象的簡單參數,具體由makeArray完成  
  115.         if (selector.selector !== undefined) 完成加{  
  116.             this.selector = selector.selector;  
  117.             this.context = selector.context;  
  118.         }  
  119.         //使用makeArray,為jQuery對象添加元素,例如$([1,2]);  
  120.         return jQuery.makeArray( selector, this );  
  121.     },  

 

從源碼可以看出,jQuery 通過各種條件判斷和強大的正則表達式,實現了各種參數的調用。

總結

$符號,其實是對jQuery類構造函數的引用,此函數實際調用了jQuery.fn.init(即是jQuery.prototype.init)來生成jQuery對象,其中jQuery.prototype的所有方法都被jQuery的對象繼承。$.func實際是jQuery類的靜態方法,所以$即是jQuery類的構造函數,支持各種條件的查找和生成並返回DOM對象構成jQuery對象,同時也是一個類,是所有jQuery靜態方法的入口,例如可以使用個$.ajax()。

最后,奉送一些資源給大家,14條改善jQuery代碼的技巧
關於jQuery Sizzle選擇器,有興趣的同學可以參閱初探 jQuery 的 Sizzle 選擇器


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM