DIV CSS 佈局教程網

揭開 jQuery 的執行個體建立與原型繼承機制
編輯:JQuery特效代碼     

我們很熟悉 new Object()、new Date() 這類寫法(物件有 {}、陣列有 [] 這種簡寫,這裡主要討論 new 的方式)。

但使用 jQuery 時從來沒寫過 new,它是用別的方法產生執行個體嗎?難道沒用到 prototype?事實上兩者都用到了,只是內部處理得非常巧妙,讓使用起來特別順手。來看原始碼。

. 程式碼如下:

funtion jQuery( selector, context){
return new jQuery.fn.init( selector, context );
}

由此可見 jQuery 有建構函式,也確實用了 new 建立執行個體。那 jQuery.fn 是什麼?後面有這樣一段:

. 程式碼如下:

jQuery.fn = jQuery.prototype={
init:function (){}
}

於是就清楚了:真正的建構函式是原型上的 init,而不是 function jQuery。每次呼叫 $(),jQuery 都用原型上的 init 建立一個執行個體。

問題來了:用 init 建立的執行個體,繼承的是 init 的 prototype 上的方法,不會繼承 jQuery.prototype 上的方法,那它是怎麼完成原型繼承的?

關鍵在這一行:

jQuery.fn.init.prototype = jQuery.fn;

把 jQuery.fn 指定給 jQuery.fn.init.prototype,我們來拆解一下:

jQuery.fn 就是 jQuery.prototype

jQuery.fn.init.prototype 就是 jQuery.prototype.init.prototype

這個處理相當於

jQuery.prototype = jQuery.prototype.init.prototype

所以每次呼叫 $(),jQuery 就用 new 呼叫原型上的 init 建立執行個體,這個由 init 產生的執行個體會繼承 jQuery.prototype 上的所有方法,其實部的 __proto__ 屬性會指向 jQuery 的 prototype。

另外還有一個小細節:

jQuery.fn = jQuery.prototype

這是為了避免頻繁操作 jQuery.prototype,用 jQuery.fn 做一份快取。

這些處理相當巧妙:內部完成執行個體建立,使用者不必寫 new;同時漂亮地處理好 prototype,讓多個執行個體共享方法,減少資源消耗。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved