将插件分配给 jQuery 原型(prototype)属性。当 jQuery 不使用“new”时,这样做有什么意义呢? jQuery 的实例只有一个,不是吗?那么插件不能直接分配给单例 jQuery 对象吗?
最佳答案
插件方法必须自动添加到创建的每个新 jQuery 对象中。
jQuery.fn
与 jQuery.prototype
相同,因此将插件方法分配给 jQuery.fn
会将其添加到 jQuery 原型(prototype)所以每当创建一个新的 jQuery 对象时,该方法将自动可用。从技术上讲,它是一个 jQuery.fn.init
对象,但想法是相同的。
使用如下字符串调用 jQuery:
$(".foo")
创建一个新的 jQuery.fn.init 对象,该对象从 jQuery.fn(定义插件方法的地方)获取其原型(prototype)。
下面是显示创建新对象的相关 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 - 为什么 jQuery 对插件使用原型(prototype)属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12548952/