为什么jQuery这样做:jQuery.fn.init.prototype = jQuery.fn?

一个小问题是为什么jQuery会这样做

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

为什么不简单地将f1()等添加到init.prototype ? 它只是审美还是有一些深刻的想法?

jQuery.fn只是jQuery.prototype的别名。 我认为它的定义是美观和较少打字的原因。

所以

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

实际上是

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

为什么需要这样做,这个论坛post很有帮助:

它为init()函数提供了与jQuery对象相同的原型。 所以当你在“return new jQuery.fn.init(selector,context);”中调用init()作为构造函数时, 声明,它将该原型用于它构造的对象。 这使得init()可以替代jQuery构造函数本身。

您实现的是从jQuery.fn.init构造函数返回的对象可以访问jQuery方法。

函数jQuery.fn.init是在调用jQuery(".some-selector")$(".some-selector")时执行的函数。 你可以在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 ); } 

所以,事实上,你提到的那条线对jQuery如何允许jQuery对象添加function至关重要,无论是在jQuery本身内部还是从插件中。 这是一行:

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

通过将jQuery.fn指定为此函数的原型(并且因为第一个片段使用’new’将jQuery.fn.init视为构造函数),这意味着通过jQuery.fn.whatever添加的function。对象可立即使用由所有jQuery调用返回。

例如,一个简单的jQuery插件可能会像这样创建和使用:

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

当您在第一行声明’jQuery.fn.foo’时,您实际在做的是将该函数添加到使用jQuery函数创建的所有jQuery对象的原型,如第二行中的那个。 这允许您在jQuery函数的结果上简单地调用’foo()’并调用您的插件函数。

简而言之,如果实现细节发生变化,如果jQuery中不存在这一行,那么编写jQuery插件会更加冗长,并且会受到未来破坏的影响。