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
573 views
in Technique[技术] by (71.8m points)

javascript - Why jQuery do this: jQuery.fn.init.prototype = jQuery.fn?

Little extended question is why jQuery do

jQuery.fn = jQuery.prototype = {
init: function() {...},
    f1: function() {...},
    ...
};
jQuery.fn.init.prototype = jQuery.fn;

Why not simply add f1() etc into init.prototype? Is it only aesthetic or there are some deep ideas?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The function jQuery.fn.init is the one that is executed when you call jQuery(".some-selector") or $(".some-selector"). You can see this in this snippet from jquery.js:

jQuery = window.jQuery = window.$ = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context );
}

So, in fact, the line you mention is critical to how jQuery allows the addition of functionality to jQuery objects, both inside jQuery itself and from plugins. This is the line:

jQuery.fn.init.prototype = jQuery.fn;

By assigning jQuery.fn as the prototype of this function (and because the first snippet uses 'new' to treat jQuery.fn.init as a constructor), this means the functionality added via jQuery.fn.whatever is immediately available on the objects returned by all jQuery calls.

So for example, a simple jQuery plugin might be created and used like this:

jQuery.fn.foo = function () { alert("foo!"); };
jQuery(".some-selector").foo();

When you declare 'jQuery.fn.foo' on the first line what you're actually doing is adding that function to the prototype of all jQuery objects created with the jQuery function like the one on the second line. This allows you to simple call 'foo()' on the results of the jQuery function and invoke your plugin functions.

In short, writing jQuery plugins would be more verbose and subject to future breakage if the implementation details changed if this line didn't exist in jQuery.


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

...