分享

$到底是什么

 当年剩女图书馆 2013-08-25

$到底是什么-详解jQuery的$符号和init函数

前言

本文所有代码,出自jQuery.1.5.2,为方便理解,引入类的概念,虽然jQuery不是基于面向对象思想。

jQuery是现在最流行的Javascript框架, $是其中最常见的符号,已经在jQuery留下了深深的烙印。
那么$到底是什么东西,它可以接受一个字符,也可以接受一个文档对象,亦或者一个函数,也可以调用一个函数。
接下来我会彻底分析这个符号背后隐藏的秘密。

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

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

熟悉jQuery的人应该知道,几乎jQuery所有操作,都是从$符号开始,当作为元素选择器的时候,操作结果返回的是一个jQuery对象。
那么,现在就看jQuery类的构造函数的主要代码

jQuery对象的构造函数

1var jQuery = (function() {
2    //创建jQuery对象,给所有的jQuery方法提供统一的入口,避免繁琐难记
3    var jQuery = function( selector, context ) {
4        //jQuery的构造对象,调用了jQuery.fn.init方法
5        //最后返回jQuery.fn.init的对象
6        return new jQuery.fn.init( selector, context, rootjQuery );
7    },
8 
9    .....
10 
11    //定义jQuery的原型,jQuery.fn指向jQuery.prototype对象
12    jQuery.fn = jQuery.prototype = {
13    //重新指定构造函数属性,因为默认指向jQuery.fn.init
14    constructor: jQuery,
15    init: function( selector, context, rootjQuery ) {.....},
16 
17    ......
18 
19    }
20 
21    ......
22 
23    //返回jQuery变量,同时定义将全局变量window.jQuery和window.$指向jQuery
24    return (window.jQuery = window.$ = jQuery);
25 
26})();

从以上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的真实构造器,我们就可以完全清楚了

init源码

1/*所有查找或生成元素的结果,封装为jQuery对象数组返回.
2    */
3    init: function( selector, context, rootjQuery ) {
4        var match, elem, ret, doc;
5 
6        // 1)处理 $(""), $(null), or $(undefined)
7        //this指向jQuery对象
8        if ( !selector ) {
9            return this;
10        }
11 
12        // 2)处理 $(DOMElement)
13        //selector.nodeType得知为DOM元素,如果是DOM元素直接放进jQuery对象数组中
14        if ( selector.nodeType ) {
15            this.context = this[0] = selector;
16            this.length = 1;
17            return this;
18        }
19 
20        //3)body元素只出现一次, 优化查找
21        if ( selector === "body" && !context && document.body ) {
22            this.context = document;
23            this[0] = document.body;
24            this.selector = "body";
25            this.length = 1;
26            return this;
27        }
28 
29        //4)如果是字符串,有六种情况,
30        /*
31        *(1)单个html元素 不带属性对象字面量 :createElement + merge
32        *(2)单个html元素 带属性对象字面量 :createElement + attr + merge
33        *(3)多个html元素  :buildFragment + merge
34        *(4)#id 不带context   :getElementById或者getElementById + Sizzle
35        *(5)#id 带context :Sizzle
36        *(6)experession string :Sizzle
37        *(7)标签选择器 :Sizzle(内置getElementByTagName)
38        */
39        if ( typeof selector === "string" ) {
40            // 判断是否为HTML string 还是 ID
41            //如果是HTML strings  match[1] 非空
42            //如果是ID strings match[1] 空
43            //quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,
44            match = quickExpr.exec( selector );
45 
46            // 分析匹配结果,且当#id没有context参数,例如不是$('#xxx',xxx)
47            if ( match && (match[1] || !context) ) {
48 
49                // 处理HTML字符 $(html) -> $(array)
50                if ( match[1] ) {
51                    //如果context为jQuery对象,则取用第一个元素,即是context[0]
52                    context = context instanceof jQuery ? context[0] : context;
53                    //取得document文档
54                    doc = (context ? context.ownerDocument || context : document);
55 
56                    //判断是否为单个元素字符串
57                    ret = rsingleTag.exec( selector );
58                    //单个元素
59                    if ( ret ) {
60                        //带对象属性字面量
61                        //检查context是否为对象字面量,适用场景
62                        //例如$('<div>', { 'id': 'test', 'class': 'test' });
63                        if ( jQuery.isPlainObject( context ) ) {
64                            selector = [ document.createElement( ret[1] ) ];
65                            jQuery.fn.attr.call( selector, context, true );
66 
67                        } else {
68                        //不带对象字面量
69                        //例如$('<div>')
70                            selector = [ doc.createElement( ret[1] ) ];
71                        }
72 
73                    } else {
74                        //如果是多个元素字符串,例如$('<div><a></a></div>')
75                        ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
76                        selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
77                    }
78                    //将生成结果selector 合并到jQuery对象中
79                    return jQuery.merge( this, selector );
80 
81                // 处理$("#id"),例如$("#xxx");
82                } else {
83                    elem = document.getElementById( match[2] );
84 
85                    if ( elem && elem.parentNode ) {
86                        //处理IE和Opera ID 与 Name 混淆的bug,使用Sizzle查找
87                        if ( elem.id !== match[2] ) {
88                            return rootjQuery.find( selector );
89                        }
90 
91                        // 否则,简单插入jQuery对象数组
92                        this.length = 1;
93                        this[0] = elem;
94                    }
95 
96                    this.context = document;
97                    this.selector = selector;
98                    return this;
99                }
100 
101            // 处理 $(expr, $(...)),使用Sizzle查找,例如$("div"),$('div > a'),$('div,a'),$('div:first')
102            } else if ( !context || context.jquery ) {
103                return (context || rootjQuery).find( selector );
104 
105            // 处理: $(expr, context),例如$('div a');或者$('a','div')或者$('div').find('a');
106            } else {
107                return this.constructor( context ).find( selector );
108            }
109 
110        //5)处理: $(function),设置DOM载的时候绑定的函数,等同于$().ready(){foo}
111        } else if ( jQuery.isFunction( selector ) ) {
112            return rootjQuery.ready( selector );
113        }
114        //6)处理:$($(...)),完成克隆jQuery对象的简单参数,具体由makeArray完成
115        if (selector.selector !== undefined) 完成加{
116            this.selector = selector.selector;
117            this.context = selector.context;
118        }
119        //使用makeArray,为jQuery对象添加元素,例如$([1,2]);
120        return jQuery.makeArray( selector, this );
121    },

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

总结

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

最后,奉送一些资源给大家,14条改善jQuery代码的技巧
关于jQuery Sizzle选择器,有兴趣的同学可以参阅初探 jQuery 的 Sizzle 选择器

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多