为什么jQuery使用插件的prototype属性?

时间:2012-09-23 01:05:57

标签: jquery

One为jQuery prototype属性分配一个插件。当一个人不使用jQuery的'new'时,有什么意义呢?只有一个jQuery实例不存在?所以无法将插件直接分配给singleton jQuery对象吗?

1 个答案:

答案 0 :(得分:3)

必须自动将插件方法添加到每个创建的新jQuery对象中。

jQuery.fnjQuery.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;