jquery源代碼解讀筆記

1,整體結構如下

( function () {
// ……
})();
第一對括號裏是一個匿名函數,第一對括號表示執行該函數。
注: js的匿名函數模式   http://www.hedgerwow.com/360/dhtml/js-anonymous-function-patterns.html
非匿名函數的類似寫法如下
function test(){alert('test');})();
所有的jquery代碼都放在該匿名函數裏,避免了命名衝突。但有兩個要單獨處理:'jQuery'和'$'

// Map over jQuery in case of overwrite
var _jQuery = window.jQuery,
// Map over the $ in case of overwrite
    _$ = window.$;

var jQuery = window.jQuery = window.$ = function( selector, context ) {
    
// The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context );
};
noConflict: function( deep ) {
        window.$ 
= _$;

        
if ( deep )
            window.jQuery 
= _jQuery;

        
return jQuery;
    },
假如沒有執行noConflict,則原來定義的$或jQuery(如果定義了的話)會被一個新函數覆蓋,只在內部留一個原來的引用(名叫_$或_jQuery)。
如果要兼容原來的$,則執行jQuery.noConflict(),然後只能用jQuery的寫法;
極端情況:"jQuery"也被佔用了,又要兼容,那麼執行var myJQ =jQuery.noConflict(true),以後全用myJQ的寫法。
注意:這時jquery.js要放在其他js的後面。
2,
 定義jQuery的構造和原型函數,這個過程同時定義了prototype的別名爲fn:jQuery.prototype=jQuery.fn。 jQuery對象的原型prototype包括了諸多的核心方法和屬性:
init
jquery 當前的版本號
size 返回了length屬性
length
get
each
...
定義完了以後必須寫以下代碼,不明白
// Give the init function the jQuery prototype for later instantiation(晚初始化?)
jQuery.fn.init.prototype = jQuery.fn;
http://bbs.blueidea.com/thread-2843388-1-1.html
jQuery.prototype.init( selector, context )是jQuery對象的一個成員函數,但是在jQuery構造函數中總是會執行這個函數,所以說"它是加強的構造函數(init constructor 'enhanced')。因爲在執行構造函數jQuery 時總是會執行它。 這也是很多框架的典型做法。
jQuery有3個身份,類,對象,函數(構造函數)。
如果find是對象的方法,即類似於 jQuery.find=function(){}
那麼就應該使用jQuery.find();

如果find是類的成員函數,即類似於 jQuery.prototype.find=function(){}
那麼必須通過jQuery()返回jQuery實例,再調用find方法,即jQuery().find()。

8,jQuery源碼解讀---執行過程分析
http://hi.baidu.com/zhuguoneng/blog/item/3d07e9d667e9482b06088b4c.html
發佈了0 篇原創文章 · 獲贊 0 · 訪問量 8937
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章