4
一個插件分配給jQuery原型屬性。當沒有在jQuery中使用'new'時,做這件事有什麼意義?只有一個jQuery實例不在那裏?所以不能將插件直接分配給單例jQuery對象?爲什麼jQuery使用插件的prototype屬性?
一個插件分配給jQuery原型屬性。當沒有在jQuery中使用'new'時,做這件事有什麼意義?只有一個jQuery實例不在那裏?所以不能將插件直接分配給單例jQuery對象?爲什麼jQuery使用插件的prototype屬性?
插件方法必須自動添加到每個新創建的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;
我必須失去了一些東西,然後。何時創建新的jQuery對象?我以爲只有一個。 –
@IanWarburton - 我在我的回答中添加了這一點。 – jfriend00
哦,是的,我看到... $是一個工廠方法,創建一個新的jQuery實例。 –