2009-11-18 87 views
19

小擴展的問題是爲什麼jQuery的做爲什麼jQuery這樣做:jQuery.fn.init.prototype = jQuery.fn?

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

爲什麼不能簡單地添加f1()等爲init.prototype?它僅僅是審美的還是有一些深刻的想法?

+0

我不確定在init.prototype中加入f1()是什麼意思?它不會添加任何東西,它分配原型。 – 2009-11-18 10:36:34

+0

當然。當然,我的意思是「分配」。對不起我的英語不好。問題是關於爲什麼不簡單地將所有函數分配給init.prototype?爲什麼將它們分配給jQuery.prototype而不是jQuery.prototype分配給jQuery.prototype.init.prototype – NilColor 2009-11-19 09:54:05

+0

有關jQuery設計模式的相關問題:http://stackoverflow.com/q/12143590/1048572 – Bergi 2013-02-11 19:15:43

回答

20

jQuery.fn只是jQuery.prototype的別名。我認爲它是爲美學和較少的打字原因而定義的。

所以

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

實際上是

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

至於爲什麼需要做的,這forum post是有幫助的:

它給人的init()函數相同 原型作爲jQuery對象。所以當你在「return new jQuery.fn.init( selector,context)」中調用init()作爲構造函數 時,所以 ;聲明,它 使用該對象的原型構造它。這可以讓init() 替代jQuery構造函數 本身。

您實現的是從jQuery.fn.init構造函數返回的對象可以訪問jQuery方法。

+0

是的。我知道'.fn'是'.prototype'的快捷方式。 但爲什麼他們擴展jQuery.prototype並且做了'jQuery.fn.init.prototype = jQuery.fn'?爲什麼不直接擴展'jQuery.fn.init.prototype'? – NilColor 2009-11-18 10:49:59

+0

感謝您的論壇鏈接。它幫助我很多! – NilColor 2009-11-19 12:11:49

47

功能jQuery.fn.init是在您撥打jQuery(".some-selector")$(".some-selector")時執行的功能。您可以在該段從jquery.js看到這一點:

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

所以,其實,你提到的線是jQuery的允許添加的功能,jQuery的對象關鍵,內外jQuery的本身和插件。這是行:

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

通過如該函數的原型分配jQuery.fn(和由於第一代碼段使用「新」治療jQuery.fn.init作爲構造)時,這意味着通過jQuery.fn.whatever加入的功能性立即可用於所有jQuery調用返回的對象。

因此,例如,可能會創建一個簡單的jQuery插件,並使用這樣的:

jQuery.fn.foo = function() { alert("foo!"); }; 
jQuery(".some-selector").foo(); 

當你聲明的第一行你實際上做的是加入什麼「jQuery.fn.foo」函數用於使用jQuery函數創建的所有jQuery對象的原型,如第二行的jQuery對象。這使您可以簡單地調用jQuery函數結果中的'foo()'並調用您的插件函數。

簡而言之,如果在jQuery中不存在此行,則如果實現細節發生更改,編寫jQuery插件將會更加冗長,並且會受到將來的破壞。

+2

優秀的答案,對我來說真的很有意義 – 32423hjh32423 2010-01-21 12:30:08

+0

這是我在這麼多時間閱讀的最顯着的評論。謝謝。 – asumaran 2013-07-10 07:08:31

+0

對不起,在答案/註釋中注入了一個問題,但我們是否說過以這種方式向jQuery添加函數會使該函數對頁面上的每個元素都可用?它是否使該函數可用於元素之外的其他元素,如其他jQuery對象等?而且,「jQuery = window.jQuery = window。$ = function(...」僅僅是一種顯示所有三種語法都是等價的語法的方法嗎?或者這實際上是你會做的事情? – 2016-01-19 18:29:15