JQuery创建实例历程

本文详细解读jQuery源码,揭示其实现机制,包括如何将$(selector)调用转化为jQuery.fn.init实例化,以及jQuery.fn.init实例的prototype继承jQuery.prototype属性和方法的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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上的属性和方法。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值