Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

in jQuery what is the difference between $.myFunction and $.fn.myFunction?

I'm delving into writing plugins for jQuery and I'm trying to understand the distinction between $.f and $.fn.f

I've seen pluggin authors use both, or sometimes assign $.f = $.fn.f

Can someone explain this to me, reasoning, benefits, etc?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Looking at the jQuery source code will clear things up. By the way, jQuery and $ refer to the same object, and this is how the jQuery object is defined:

var jQuery = function( selector, context ) {
    return new jQuery.fn.init( selector, context );
}

jQuery is a function and in Javascript, a function is also an object of the type Function. So jQuery.f or $.f attaches f to the jQuery Function object, or call it the jQuery class if you will.

if you look at jQuery's source, you'll see that jQuery.prototype has been assigned to jQuery.fn

jQuery.fn = jQuery.prototype

So, whenever you attach a method (or property) to jQuery.fn, as in jQuery.fn.f = .., or $.fn.f = .., or jQuery.prototype.f = .., or $.prototype.f = .., that method will be available to all instances of this jQuery class (again, there are no classes in Javascript, but it may help in understanding).

Whenever you invoke the jQuery() function, as in jQuery("#someID"), a new jQuery instance is created on this line:

return new jQuery.fn.init( selector, context );

and this instance has all the methods we attached to the prototype, but not the methods that were attached directly to the Function object.

You will get an exception if you try calling a function that wasn't defined at the right place.

$.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();

Oh, and finally to cut a long thread short and to answer your question - doing $.f = $.fn.f allows you to use the function as a plugin or a utility method (in jquery lingo).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...