我正在深入研究jQuery的插件,我试图理解$ .f和$ .fn.f之间的区别
我见过插件作者使用两者,或者有时会分配$ .f = $ .fn.f
有人可以向我解释这个,推理,好处等吗?
Anu*_*rag 13
查看jQuery源代码将清除问题.顺便说一下,jQuery
并$
引用同一个对象,这就是jQuery对象的定义方式:
var jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context );
}
Run Code Online (Sandbox Code Playgroud)
jQuery
是一个函数,在Javascript中,函数也是该类型的对象Function
.所以jQuery.f
或者$.f
附加f
到jQuery Function
对象,或者如果你愿意,可以将它称为jQuery类.
如果你看一下jQuery的源代码,你会看到jQuery.prototype
已经分配了jQuery.fn
jQuery.fn = jQuery.prototype
Run Code Online (Sandbox Code Playgroud)
因此,无论何时将方法(或属性)附加到jQuery.fn
,jQuery.fn.f = ..
或者$.fn.f = ..
,或者jQuery.prototype.f = ..
,或者$.prototype.f = ..
,该方法将可用于此jQuery类的所有实例(同样,Javascript中没有类,但它可能有助于理解).
无论何时调用该jQuery()
函数,jQuery("#someID")
都会在此行中创建一个新的jQuery实例:
return new jQuery.fn.init( selector, context );
Run Code Online (Sandbox Code Playgroud)
并且此实例具有我们附加到原型的所有方法,但不包含直接附加到Function
对象的方法.
如果您尝试调用未在正确位置定义的函数,则会出现异常.
$.doNothing = function() {
// oh noez, i do nuttin
}
// does exactly as advertised, nothing
$.doNothing();
var jQueryEnhancedObjectOnSteroids = $("body");
// Uncaught TypeError: Object #<an Object> has no method 'doNothing'
jQueryEnhancedObjectOnSteroids.doNothing();
Run Code Online (Sandbox Code Playgroud)
哦,最后切断一个很长的线程并回答你的问题 - 做$.f = $.fn.f
允许你使用该函数作为插件或实用程序方法(在jquery lingo中).