我reading this article about how jQuery works,這條精縮jQuery的結構爲象徵代碼:#32
jQuery結構 - 澄清?
/*1*/ var jQuery = (function()
/*2*/ {
/*3*/
/*4*/
/*5*/ var jQuery = function (selector, context)
/*6*/ {
/*7*/
/*8*/
/*9*/ return new jQuery.fn.init(selector, context, rootjQuery);
/*10*/ },
/*11*/ rootjQuery;
/*12*/
/*13*/
/*14*/ jQuery.fn = jQuery.prototype = {
/*15*/ constructor: jQuery,
/*16*/ init: function (selector, context, rootjQuery)
/*17*/ {
/*18*/
/*19*/ if (!selector)
/*20*/ {
/*21*/ return this;
/*22*/ }
/*23*/ },
/*24*/ //I screwed with the core!
/*25*/
/*26*/ yo: function()
/*27*/ {
/*28*/ alert("yo")
/*29*/ },
/*30*/ };
/*31*/
/*32*/ jQuery.fn.init.prototype = jQuery.fn;
/*33*/
/*34*/ // Expose jQuery to the global object
/*35*/ return jQuery;
/*36*/ })();
行是魔法發生。所以當我寫jQuery(..)
它實際上運行new init()
有權訪問所有jQuery.fn
函數。
這是很清楚的(大部分),但我有2個問題:
問題#1爲什麼存在線#15
(constructor: jQuery,
)?它所做的(imho)是告訴prototype
對象它的ctor function
是jQuery
。 jQuery如何使用這個事實?
問題2縱觀線#14
,這顯然(在我們的例子功能yo
- 線#26
)添加功能jQUery.fn
。
但是爲什麼jQuery.prototype
(線#14中)也具有這些功能(它設置他們是prototype
...)?這就像我們要做$.addClass()
這是無效。
[差異的價值,原型和屬性]可能的重複(http://stackoverflow.com/questions/12143590/difference-of-the-value-prototype-and-property) – Bergi
@Bergi您的答案不回答我的問題#1。你只是描述了這個事實。而已。關於我的問題#2,我不會在那裏寫下你的措辭:「對於那些不使用fn財產的人」 - 你能否詳細說明一下? –
好吧,我會帶更具體的答案 – Bergi