您的位置:首页 > Web前端 > JQuery

【jquery】$到底是什么-详解jQuery的$符号和init函数(热荐)

2014-03-31 17:35 441 查看
本文所有代码,出自jQuery.1.5.2,为方便理解,引入类的概念,虽然jQuery不是基于面向对象思想。

jQuery是现在最流行的Javascript框架, $是其中最常见的符号,已经在jQuery留下了深深的烙印。

那么$到底是什么东西,它可以接受一个字符,也可以接受一个文档对象,亦或者一个函数,也可以调用一个函数。

接下来我会彻底分析这个符号背后隐藏的秘密。

jQuery,高效,精炼,特别是对DOM元素对象操作的简化,很大程度上将前端程序员从一大堆冗余的代码解放出来,大大提高了开发效率!对多浏览器的兼容性,也最大限度让程序员摆脱各种bug的纠缠

$符号作为元素选择器的简写,最早是由Prototype库使用,来简写getElementById,jQuery沿袭这一理念,并发扬光大,使$符号成为了jQuery最别具一格的特点。那么在jQuery中,$符号到底是啥?

熟悉jQuery的人应该知道,几乎jQuery所有操作,都是从$符号开始,当作为元素选择器的时候,操作结果返回的是一个jQuery对象。

那么,现在就看jQuery类的构造函数的主要代码


jQuery对象的构造函数

var jQuery = (function() {
//创建jQuery对象,给所有的jQuery方法提供统一的入口,避免繁琐难记
var jQuery = function( selector, context ) {
//jQuery的构造对象,调用了jQuery.fn.init方法
//最后返回jQuery.fn.init的对象
return new jQuery.fn.init( selector, context, rootjQuery );
},

.....

//定义jQuery的原型,jQuery.fn指向jQuery.prototype对象
jQuery.fn = jQuery.prototype = {
//重新指定构造函数属性,因为默认指向jQuery.fn.init
constructor: jQuery,
init: function( selector, context, rootjQuery ) {.....},

......

}

......

//返回jQuery变量,同时定义将全局变量window.jQuery和window.$指向jQuery
return (window.jQuery = window.$ = jQuery);

})();


从以上jQuery的主体结构,我们可以看出,当首次执行完毕后,全局变量$和jQuery,都是指向了var jQuery=function(selector,context){}这个函数,这里,就可以下个结论,$就是jQuery的别名,实际调用jQuery.fn.init

再看看var jQuery=function(selector,context){}这个构造函数,为什么里面不直接返回jQuery的对象?而是调用另外一个方法呢?

假如直接返回对象的话,每次使用jQuery对象,都要new jQuery() 这样的话,十分不方便,直接将new 这个操作封装在jQuery构造函数里面,简化了实例化的操作,同时,jQuery通过了jQuery或者$符号,统一了接口,方便代码的编写,化繁为简,提高效率。

那么jQuery类具体是如何构造的?居然能支持各种参数形式的调用

直接上jQuery.fn.init的“辕马”,jQuery的真实构造器,我们就可以完全清楚了

/*所有查找或生成元素的结果,封装为jQuery对象数组返回.
*/
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;

// 1)处理 $(""), $(null), or $(undefined)
//this指向jQuery对象
if ( !selector ) {
return this;
}

// 2)处理 $(DOMElement)
//selector.nodeType得知为DOM元素,如果是DOM元素直接放进jQuery对象数组中
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}

//3)body元素只出现一次, 优化查找
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = "body";
this.length = 1;
return this;
}

//4)如果是字符串,有六种情况,
/*
*(1)单个html元素 不带属性对象字面量 :createElement + merge
*(2)单个html元素 带属性对象字面量 :createElement + attr + merge
*(3)多个html元素  :buildFragment + merge
*(4)#id 不带context	:getElementById或者getElementById + Sizzle
*(5)#id 带context :Sizzle
*(6)experession string :Sizzle
*(7)标签选择器 :Sizzle(内置getElementByTagName)
*/
if ( typeof selector === "string" ) {
// 判断是否为HTML string 还是 ID
//如果是HTML strings  match[1] 非空
//如果是ID strings match[1] 空
//quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,
match = quickExpr.exec( selector );

// 分析匹配结果,且当#id没有context参数,例如不是$('#xxx',xxx)
if ( match && (match[1] || !context) ) {

// 处理HTML字符 $(html) -> $(array)
if ( match[1] ) {
//如果context为jQuery对象,则取用第一个元素,即是context[0]
context = context instanceof jQuery ? context[0] : context;
//取得document文档
doc = (context ? context.ownerDocument || context : document);

//判断是否为单个元素字符串
ret = rsingleTag.exec( selector );
//单个元素
if ( ret ) {
//带对象属性字面量
//检查context是否为对象字面量,适用场景
//例如$('<div>', { 'id': 'test', 'class': 'test' });
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );

} else {
//不带对象字面量
//例如$('<div>')
selector = [ doc.createElement( ret[1] ) ];
}

} else {
//如果是多个元素字符串,例如$('<div><a></a></div>')
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
}
//将生成结果selector 合并到jQuery对象中
return jQuery.merge( this, selector );

// 处理$("#id"),例如$("#xxx");
} else {
elem = document.getElementById( match[2] );

if ( elem && elem.parentNode ) {
//处理IE和Opera ID 与 Name 混淆的bug,使用Sizzle查找
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}

// 否则,简单插入jQuery对象数组
this.length = 1;
this[0] = elem;
}

this.context = document;
this.selector = selector;
return this;
}

// 处理 $(expr, $(...)),使用Sizzle查找,例如$("div"),$('div > a'),$('div,a'),$('div:first')
} else if ( !context || context.jquery ) {
return (context || rootjQuery).find( selector );

// 处理: $(expr, context),例如$('div a');或者$('a','div')或者$('div').find('a');
} else {
return this.constructor( context ).find( selector );
}

//5)处理: $(function),设置DOM载的时候绑定的函数,等同于$().ready(){foo}
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
//6)处理:$($(...)),完成克隆jQuery对象的简单参数,具体由makeArray完成
if (selector.selector !== undefined) 完成加{
this.selector = selector.selector;
this.context = selector.context;
}
//使用makeArray,为jQuery对象添加元素,例如$([1,2]);
return jQuery.makeArray( selector, this );
},


从源码可以看出,jQuery 通过各种条件判断和强大的正则表达式,实现了各种参数的调用。


总结

$符号,其实是对jQuery类构造函数的引用,此函数实际调用了jQuery.fn.init(即是jQuery.prototype.init)来生成jQuery对象,其中jQuery.prototype的所有方法都被jQuery的对象继承。$.func实际是jQuery类的静态方法,所以$即是jQuery类的构造函数,支持各种条件的查找和生成并返回DOM对象构成jQuery对象,同时也是一个类,是所有jQuery静态方法的入口,例如可以使用个$.ajax()。

jquery类中的静态方法跟java类中的static方法类似,无需实例化即可使用,如下:

$-JQuery类

$("#one")-JQuery对象,内部是通过new JQuery.fn.init("#one")创建的一个对象

插件的开发:常用的两种方法

jQuery.extend(object); 为扩展jQuery类本身.为类添加新的方法。

jQuery.fn.extend(object);给jQuery对象添加方法。

jquery本身没有类的概念,但是有时候我们为了使得问题更加容易理解,才引入了类的概念
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: