javascript物件導向的寫法及jQuery物件導向的寫法

來源:互聯網
上載者:User

標籤:

文章由來:jQuery源碼學習時的總結

在JS中,一般的物件導向的寫法如下:

function Cao(){}//定義一個建構函式Cao.prototype.init = function(){}//原型上添加初始化方法Cao.prototype.other = function(){}//可執行檔其他實際方法var c1 = new Cao();//執行個體化對象c1.init();//初始化c1.css();//操作函數

定義一個對象Cao,執行個體化c1,c1.init()初始化,c1.other()調用其他可用方法,這樣的做法比較麻煩,每次調用都需要執行個體化c1,然後初始化c1.init(),最後才可以調用其他方法。
jQuery的做法是:

function jQuery(){return new jQuery.prototype.init();}jQuery.prototype.init = function(){}jQuery.prototype.other = function(){}jQuery.prototype.init.prototype = jQuery.prototype;//這句話可以先忽略,下面會講jQuery().other();

只有一行

jQuery().other();

代碼就完成了所有工作,為什嗎?

分析下:

調用jQuery(),實際上完成了執行個體化和初始化的過程,因為jQuery()返回jQuery.prototype.init()的初始化對象。

 

jQuery->jQuery.prototype

jQuery->jQuery.prototype->jQuery.prototype.init

 

像上面的關係那樣,返回的 new jQuery.prototype.init(),在jQuery的原型上,jQuery.prototype.init()上根本沒有other()方法,如何讓jQuery.prototype.init()也能操作other()呢?

 

所以就有了這樣一句話:

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

這句話是把jQuery原型的引用賦值給jQuery.prototype.init原型,像下面所示:

 

jQuery->jQuery.prototype

jQuery->jQuery.prototype->jQuery.prototype.init->jQuery.prototype.init.prototype->jQuery.prototype

 

這樣在jQuery.prototype.init的原型上就有了jQuery原型的引用。

那jQuery()返回的jQuery.prototype.init(),實際上就包含了jQuery對象上的所有內容,所以jQuery().other();就是直接操作jQuery對象上的other()。

修改jQuery原型就是在修改初始化init對象的原型。

 

jQuery源碼中實際的寫法:

#61-#64行:

jQuery = function( selector, context ) {        // The jQuery object is actually just the init constructor ‘enhanced‘        return new jQuery.fn.init( selector, context, rootjQuery );},    

jQuery.fn.init是什麼鬼呢?

 

在#96有這麼一句話:

jQuery.fn = jQuery.prototype = {...}

說明jQuery.fn就是jQuery.prototype,即jQuery原型。

在#283:

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

就是jQuery.prototype.init.prototype = jQuery.prototype;

javascript物件導向的寫法及jQuery物件導向的寫法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.