2011-10-04 107 views
2

我有兩個關於下面的代碼片段的問題。 (1)JQuery源代碼問題

(1)。 「返回新的jQuery.fn.init(選擇器,上下文,rootjQuery)」的目的是什麼?爲什麼它會在JQuery函數中返回另一個實例?

(2)。爲什麼prototype.constructor被重新定義爲JQuery?

// Define a local copy of jQuery 
var jQuery = function(selector, context) { 
     // The jQuery object is actually just the init constructor 'enhanced' 
     return new jQuery.fn.init(selector, context, rootjQuery); 
    }, 

... ... 

jQuery.fn = jQuery.prototype = { 
    constructor: jQuery, 
    init: function(selector, context, rootjQuery) { 
     var match, elem, ret, doc; 

謝謝!

回答

3
  1. 當JQuery被調用爲普通函數時,會創建一個新的(類)JQuery實例並使用new JQuery.fn.init(...)返回。這樣,開發人員不必在$(..)之前添加new關鍵字。
  2. JQuery.fnJQuery.prototype的快捷方式。寫作JQuery.fn.customMethod = function(){...}比寫作JQuery.prototype.customMethod = ...更方便。由於JQuery通常也可以通過$$j訪問,因此參考JQuery.prototype的簡短方式是$.fn
+1

羅布嗨,什麼是「rootjQuery」參數?謝謝。 – Ricky

+0

'rootQuery'是引用文檔的JQuery包裝的根的內部參數。 –

1

(2)。爲什麼prototype.constructor被重新定義爲JQuery?

我認爲原因是保持每個jQuery對象內的構造函數引用,實際上它本身(它創建一個循環引用)。事實上,通過這段代碼重寫jQuery.prototype對象

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

你失去了「自動創建」構造函數(指向已從,建立在這種情況下jQuery.fn.init的功能),所以你需要明確地設置它。

我發現這個環節非常有助於理解JavaScript的原型和構造器:

http://joost.zeekat.nl/constructors-considered-mildly-confusing.html