jQuery源代码阅读之一——jQuery总体结构及jQuery构造函数

一、jQuery总体架构

jQuery作为一款强大的js库,由以下模块构成:

(function(window,undefined){
    var jQuery=function(selector,context){
        //...
    };
    //工具方法utilities
    //回调函数 callbacks
    //异步队列 Defered Object
    //浏览器功能测试 Support
    //数据缓存 Data
    //队列 Queue
    //属性操作 Attributes
    //事件系统 Events
    //选择器 Sizzle
    //DOM遍历 Traversing
    //DOM操作 Manipulation
    //样式操作 CSS
    //异步请求  Ajax
    //动画 Animation
    //坐标 offset,尺寸 Dimensions
    window.jQuery=window.$=jQuery;
}})(window);

关于上述代码,解释如下:

1.jQuery的整体代码包裹在一个立即执行的自调用匿名的函数中,这样可以尽量减少和其他第三方库的干扰;

2,在上述代码最后,将jQuery对象添加到全局window上,并为之设置变量$,从而使得可以在外界访问jQuery;

3,为自调用匿名函数设置参数window,并传入参数window,这样一方面可以缩短作用域链,可以尽快访问到window;另一方面便于代码压缩;

4,为自动用匿名函数设置参数undefined,一方面可以缩短查找Undefined的作用域链,另一方面可防止undefined在外界被修改。

二、构造jQuery对象

jQuery对象是一个类数组对象,含有连续的整型属性、length属性、context属性,selector属性(在jQuery.fn.init中设置),preObject属性(在pushStack中设置);此外,还包含非继承属性以及大量的jQuery方法。

jQuery构造函数根据传入参数不同,有7种用法,在自己尝试实现的轻量级jQuery中,暂不考虑传入复杂选择器表达式和html代码的情形。

jQuery构造函数的整体代码结构如下:

(function(window,undefined){
    var rootjQuery,
        jQuery=function(selector,context){
        return jQuery.fn.init(selector,context,rootjQuery);
    };

    jQuery.fn=jQuery.prototype={
        constructor:jQuery,
        init:function(selector,context,rootjQuery){
            //...
        }
    };

    jQuery.fn.init.prototype=jQuery.prototype;
    rootjQuery=jQuery(document);
    window.jQuery=window.$=jQuery;
}})(window);

针对上述代码,解释如下:

1)在jQuery构造函数中,使用new创建并返回另一个构造函数的实例,这样可以在创建jQuery对象时,省略运算符new而直接写jQuery;此时,在构造函数中返回的是jquery.fn.init的实例,为了保证能够在jQuery.fn.init()的实例上访问jQuery()的原型方法和属性,令 jQuery.fn.init.prototype=jQuery.prototype。

 

原文地址:https://www.cnblogs.com/bobodeboke/p/5938847.html