如 new Object()、new Date()等等!(object有{},數組有[]這樣的捷徑 ,我們主要探討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 (){}
}
這樣我們就明白了,jQuery的建構函式是他原型上的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運算子調用他prototype上的init建立一個執行個體,這個由init建立執行個體會繼承jQuery protype上的所有方法,並且這個執行個體的__proto__內部屬性會指向jQuery的prototype屬性。
另外我們注意到這個處理:
jQuery.fn = jQuery.prototype
這是他為了避免頻繁的操作jQuery.prototype,所以用jQuery.fn緩衝了jQuery.prototype。
這些的處理實在是非常巧妙,內部處理了執行個體建立不用使用者用new去產生執行個體,又非常漂亮的處理了prototype保證多執行個體共用方法減少資源開支。