2014-03-07 39 views
5

reading this article about how jQuery works,這條精縮jQuery的結構爲象徵代碼:#32jQuery結構 - 澄清?

/*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爲什麼存在線#15constructor: jQuery,)?它所做的(imho)是告訴prototype對象它的ctor functionjQuery。 jQuery如何使用這個事實?

問題2縱觀線#14,這顯然(在我們的例子功能yo - 線#26)添加功能jQUery.fn

但是爲什麼jQuery.prototype(線#14中)具有這些功能(它設置他們是prototype ...)?這就像我們要做$.addClass()這是無效

+0

[差異的價值,原型和屬性]可能的重複(http://stackoverflow.com/questions/12143590/difference-of-the-value-prototype-and-property) – Bergi

+0

@Bergi您的答案不回答我的問題#1。你只是描述了這個事實。而已。關於我的問題#2,我不會在那裏寫下你的措辭:「對於那些不使用fn財產的人」 - 你能否詳細說明一下? –

+2

好吧,我會帶更具體的答案 – Bergi

回答

2

爲什麼第15行(constructor: jQuery,)存在?它所做的(imho)是告訴原型對象它的ctor函數是jQuery。

是的。人們希望找到new jQuery().constructor == jQuery

jQuery如何使用該事實?

例如,pushStack internal methoduses this.constructor()創建新實例 - 這也讓inheritance from jQuery

但爲什麼jQuery.prototype(第14行中間)也有這些[jQuery.fn]功能(它將它們設置爲它的原型...)?

this answer

一個背後的原因肯定是他們要 適應人們可能會改變jQuery.prototype代替 jQuery.fn

然而另一個有效的原因是,他們也許想 somejQueryObj instanceof jQuery到返回true,而它 通常不會。

這就像我們要做的$.addClass()這是無效的。

不,這是怎麼回事?您是否將每個(構造函數)函數的標準.prototype屬性與內部原型鏈混淆?

+0

關於你在這裏的最後回覆 - 我不明白。我的意思是:如果具有所有功能的對象被設置爲'jQuery.fn' - 沒關係。但他們也將這個對象的所有功能都設置爲'jQuery.prototype.' - 爲什麼? '$(div).addClass()'不應該在'$ .addClass()'上工作 - 我能理解嗎? –

+0

爲什麼你認爲'jQuery.prototype.addClass = ...'會使'$ .addClass'工作? – Bergi

+0

我沒有看到你的演示負責哪一行:'somejQueryObj instanceof jQuery'。我的意思是 - 'somejQueryObj'就像'$()',它的內部就像'new init()'。那麼'jQuery.fn.init.prototype'和'jQuery.prototype'(原型繼承)之間的連接在哪裏?你能告訴我那條路嗎? –