JQuery源码如下
// Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); } jQuery.fn = jQuery.prototype = { ... init: function( selector, context, rootjQuery ) { } ... } // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn;
其中
jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }
定义了jQuery变量就是一个方法,方法体就是:
function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }
所以在外部我们调用$("selector")等价于调用
new jQuery.fn.init( selector, context, rootjQuery );
返回的就是jQuery.fn.init的一个实例。
由于
jQuery.fn = jQuery.prototype jQuery.fn.init.prototype = jQuery.fn
所以
jQuery.fn.init.prototype = jQuery.prototype.init.prototype = jQuery.prototype
所以jQuery.fn.init的实例的prototype就是jQuery.prototype,因此会继承jQuery.prototype上的属性和方法。