2012-09-23 15 views

回答

3

插件方法必須自動添加到每個新創建的jQuery對象。

jQuery.fn相同jQuery.prototype所以分配一個插件的方法來jQuery.fn是將它添加到jQuery的原型,以便每當創建了新的jQuery對象時,該方法將自動可用。從技術上講,這是一個jQuery.fn.init的對象,但這個想法是一樣的。

調用jQuery的像這樣的字符串:

$(".foo") 

創建一個新對象jQuery.fn.init它得到從jQuery.fn其原型(其中插件方法被定義)。

下面是相關的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); 
}, 


// Give the init function the jQuery prototype for later instantiation 
jQuery.fn.init.prototype = jQuery.fn; 
+0

我必須失去了一些東西,然後。何時創建新的jQuery對象?我以爲只有一個。 –

+0

@IanWarburton - 我在我的回答中添加了這一點。 – jfriend00

+0

哦,是的,我看到... $是一個工廠方法,創建一個新的jQuery實例。 –

相關問題