zl程序教程

您现在的位置是:首页 >  前端

当前栏目

Jquery选择器$实现原理

jQuery原理 实现 选择器
2023-06-13 09:14:14 时间
但由于工作的原因,很久不曾做过网站项目了,也没有时间去好好研究Jquery的源码,这个疑问也一直没有得到解决了,今天,空闲之余,打开Jquery的源码看看,才明天它实现的原理,原来在加入jquery的js这个文件时,实际上是执行了一个函数,在这个函数里己经初始化了$和JQuery变量,实现这个功能源码如下(代码已删减和更改,并不影响说明实现原理):
复制代码代码如下:

(function(){
var
//Willspeedupreferencestowindow,andallowsmungingitsname.
window=this,
//Willspeedupreferencestoundefined,andallowsmungingitsname.
undefined,
//MapoverjQueryincaseofoverwrite
_jQuery=window.jQuery,
//Mapoverthe$incaseofoverwrite
_$=window.$,
jQuery=window.jQuery=window.$=function(selector,context){
//ThejQueryobjectisactuallyjusttheinitconstructor"enhanced"
returnnewjQuery.fn.init(selector,context);
},
//AsimplewaytocheckforHTMLstringsorIDstrings
//(bothofwhichweoptimizefor)
quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
//Isitasimpleselector
isSimple=/^.[^:#\[\.,]*$/;
jQuery.fn=jQuery.prototype={
init:function(selector,context){
//Makesurethataselectionwasprovided
//Makesurethataselectionwasprovided
selector=selector||document;
this[0]=selector;
this.length=1;
this.context=selector;
returnthis;
},
show:function(){
alert("this.show");
},
//Startwithanemptyselector
selector:"",
//ThecurrentversionofjQuerybeingused
jquery:"1.3.2"
};
jQuery.fn.init.prototype=jQuery.fn;
})();
functiontest(src){
alert($(src));
$(src).show();

从代码里我们可以看到有这样一个函数执行了(funtion(){})();

varwindow=this;
_jQuery=window.jQuery;
_$=window.$;

这几句代码应该是声明jQuery和$变量,至于为什么能这样子用我还没弄明白,等待高人解决!!

但我认为这并没关系,因为最重要的是下面这段代码:

jQuery=window.jQuery=window.$=function(selector,context){
returnnewjQuery.fn.init(selector,context);
};

可以看出创建jQuery.fn.init这样一个函数返回给$,这样是可以使用$实例了,但还不能访问jQuery.fn里的方法,因此需要加上后面这句:

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

实现了这些,Jquery中的其他功能就很好理解了,无非是添prototype或extend中的方法了.