這篇文章能夠說是讀這篇文章這篇文章後的總結。html
jQuery最基本的構成結構:函數
var jQuery = window.jQuery = window.$ = function(a,b){ return new jQuery.fn.init(a, b); // 1 }; jQuery.fn = jQuery.prototype = { init: function (s) { this[0] = s; this.length = 1; this.context = s; return this; // 2 }, age: function () { return this; } }; jQuery.fn.init.prototype = jQuery.fn; // 3 jQuery.extend = jQuery.fn.extend = function () { // 4 }
這是jQuery源碼一個最基本的概要實現,但從這個實現中已經能弄並學到不少東西了。this
( 1 ) 首先 $
也就是 jQuery
自己是一個函數, 但它又不是一個普通的構造函數,這從 $('div')
的這種實例直接產生不須要 new
就能夠知道,也就是它隱藏了實例 new
的過程, jQuery
自身只是一個工廠函數,它產出由它的原型上定義的 init
方法的實例,由於擁有了 new
的過程,因此實例化中的 this
都是指向了 最終產生的實例自己,因而這樣便實現了無new構建。prototype
( 2 ) 這裏在 init
函數中有一個 return this;
的操做,通常構造函數不會這樣寫,但這樣寫並不會影響 new 的結果,這參照以前new 的分解,即可以推出結果的一致( 只是返回了不一樣但值相同的變量 )。而jQuery之因此在這裏要返回 this
是有用處的,這樣最開始實例的 this
便得以保存,$('div').ready()
這樣的鏈式調用便能獲得前方的實例對象,也就是說就是 return this;
實現了鏈式調用。code
( 3 ) 那既然是原型上的 init
構造器方法構建的實例,又怎麼能獲取到 jQuery
的原型方法呢,這就須要將 init 方法的原型用 jQuery
的原型對象覆蓋。也就是 3 部分的操做。htm
( 4 ) 最後 $.extend
與 $.fn.extend
之因此會不同,只是調用時分別是jQuery
對象或jQuery.prototype
(jQuery.prototype = jQuery.fn)致使了 this
的不一樣,實際定義是是用的同一個函數。對象