本文所有代碼,出自jQuery.1.5.2,為方便理解,引入類的概念,雖然jQuery不是基於面向對象思想。
jQuery是現在最流行的JavaScript框架, $是其中最常見的符號,已經在jQuery留下了深深的烙印。
那么$到底是什么東西,它可以接受一個字符,也可以接受一個文檔對象,亦或者一個函數,也可以調用一個函數。
接下來我會徹底分析這個符號背后隱藏的秘密。
jQuery,高效,精煉,特別是對DOM元素對象操作的簡化,很大程度上將前端程序員從一大堆冗余的代碼解放出來,大大提高了開發效率!對多瀏覽器的兼容性,也最大限度讓程序員擺脫各種bug的糾纏
$符號作為元素選擇器的簡寫,最早是由Prototype庫使用,來簡寫getElementById,jQuery沿襲這一理念,並發揚光大,使$符號成為了jQuery最別具一格的特點。那么在jQuery中,$符號到底是啥?
熟悉jQuery的人應該知道,幾乎jQuery所有操作,都是從$符號開始,當作為元素選擇器的時候,操作結果返回的是一個jQuery對象。
那么,現在就看jQuery類的構造函數的主要代碼
jQuery對象的構造函數
- var jQuery = (function() {
- //創建jQuery對象,給所有的jQuery方法提供統一的入口,避免繁瑣難記
- var jQuery = function( selector, context ) {
- //jQuery的構造對象,調用了jQuery.fn.init方法
- //最后返回jQuery.fn.init的對象
- return new jQuery.fn.init( selector, context, rootjQuery );
- },
- .....
- //定義jQuery的原型,jQuery.fn指向jQuery.prototype對象
- jQuery.fn = jQuery.prototype = {
- //重新指定構造函數屬性,因為默認指向jQuery.fn.init
- constructor: jQuery,
- init: function( selector, context, rootjQuery ) {.....},
- ......
- }
- ......
- //返回jQuery變量,同時定義將全局變量window.jQuery和window.$指向jQuery
- return (window.jQuery = window.$ = jQuery);
- })();
從以上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的真實構造器,我們就可以完全清楚了
- /*所有查找或生成元素的結果,封裝為jQuery對象數組返回.
- */
- init: function( selector, context, rootjQuery ) {
- var match, elem, ret, doc;
- // 1)處理 $(""), $(null), or $(undefined)
- //this指向jQuery對象
- if ( !selector ) {
- return this;
- }
- // 2)處理 $(DOMElement)
- //selector.nodeType得知為DOM元素,如果是DOM元素直接放進jQuery對象數組中
- if ( selector.nodeType ) {
- this.context = this[0] = selector;
- this.length = 1;
- return this;
- }
- //3)body元素只出現一次, 優化查找
- if ( selector === "body" && !context && document.body ) {
- this.context = document;
- this[0] = document.body;
- this.selector = "body";
- this.length = 1;
- return this;
- }
- //4)如果是字符串,有六種情況,
- /*
- *(1)單個html元素 不帶屬性對象字面量 :createElement + merge
- *(2)單個html元素 帶屬性對象字面量 :createElement + attr + merge
- *(3)多個html元素 :buildFragment + merge
- *(4)#id 不帶context :getElementById或者getElementById + Sizzle
- *(5)#id 帶context :Sizzle
- *(6)experession string :Sizzle
- *(7)標簽選擇器 :Sizzle(內置getElementByTagName)
- */
- if ( typeof selector === "string" ) {
- // 判斷是否為HTML string 還是 ID
- //如果是HTML strings match[1] 非空
- //如果是ID strings match[1] 空
- //quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,
- match = quickExpr.exec( selector );
- // 分析匹配結果,且當#id沒有context參數,例如不是$('#xxx',xxx)
- if ( match && (match[1] || !context) ) {
- // 處理HTML字符 $(html) -> $(array)
- if ( match[1] ) {
- //如果context為jQuery對象,則取用第一個元素,即是context[0]
- context = context instanceof jQuery ? context[0] : context;
- //取得document文檔
- doc = (context ? context.ownerDocument || context : document);
- //判斷是否為單個元素字符串
- ret = rsingleTag.exec( selector );
- //單個元素
- if ( ret ) {
- //帶對象屬性字面量
- //檢查context是否為對象字面量,適用場景
- //例如$('<div>', { 'id': 'test', 'class': 'test' });
- if ( jQuery.isPlainObject( context ) ) {
- selector = [ document.createElement( ret[1] ) ];
- jQuery.fn.attr.call( selector, context, true );
- } else {
- //不帶對象字面量
- //例如$('<div>')
- selector = [ doc.createElement( ret[1] ) ];
- }
- } else {
- //如果是多個元素字符串,例如$('<div><a></a></div>')
- ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
- selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
- }
- //將生成結果selector 合並到jQuery對象中
- return jQuery.merge( this, selector );
- // 處理$("#id"),例如$("#xxx");
- } else {
- elem = document.getElementById( match[2] );
- if ( elem && elem.parentNode ) {
- //處理IE和Opera ID 與 Name 混淆的bug,使用Sizzle查找
- if ( elem.id !== match[2] ) {
- return rootjQuery.find( selector );
- }
- // 否則,簡單插入jQuery對象數組
- this.length = 1;
- this[0] = elem;
- }
- this.context = document;
- this.selector = selector;
- return this;
- }
- // 處理 $(expr, $(...)),使用Sizzle查找,例如$("div"),$('div > a'),$('div,a'),$('div:first')
- } else if ( !context || context.jquery ) {
- return (context || rootjQuery).find( selector );
- // 處理: $(expr, context),例如$('div a');或者$('a','div')或者$('div').find('a');
- } else {
- return this.constructor( context ).find( selector );
- }
- //5)處理: $(function),設置DOM載的時候綁定的函數,等同於$().ready(){foo}
- } else if ( jQuery.isFunction( selector ) ) {
- return rootjQuery.ready( selector );
- }
- //6)處理:$($(...)),完成克隆jQuery對象的簡單參數,具體由makeArray完成
- if (selector.selector !== undefined) 完成加{
- this.selector = selector.selector;
- this.context = selector.context;
- }
- //使用makeArray,為jQuery對象添加元素,例如$([1,2]);
- return jQuery.makeArray( selector, this );
- },
從源碼可以看出,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 選擇器