jQuery study notes: jQuery code structure

jQuery study notes: jQuery code structure

This is the notes I took in the process of learning jQuery. This part mainly includes the outermost structure of the jQuery code. I write it out and organize my learning results. If there are any mistakes, please point out.

jQuery's outermost $,jQuery

(function (global, factory) {
    "use strict";
    if (typeof module === "object" && typeof module.exports === "object") { // 判断是否使用 commonjs 环境
        module.exports = global.document ?
            factory(global, true) :
            function (w) {
                if (!w.document) {
                    throw new Error("jQuery requires a window with a document");
                }
                return factory(w);
            };
    } else {
        factory(global);
    }
})(typeof window !== "undefined" ? window : this,  function (window, noGlobal){
    if (typeof define === "function" && define.amd) {  // 是否使用 AMD 模块化规范
        define("jquery", [], function () {
            return jQuery;
        });
    }
    var
        _jQuery = window.jQuery,
        _$ = window.$;
    jQuery.noConflict = function (deep) {
        if (window.$ === jQuery) {
            window.$ = _$;
        }
        if (deep && window.jQuery === jQuery) {
            window.jQuery = _jQuery;
        }
        return jQuery;
    };
    if (!noGlobal) {
        window.jQuery = window.$ = jQuery;
    }
    return jQuery;
});

The above is part of the code of jQuery-3.3.1, which is the outermost part and contains a lot of information.

(function (global, factory) {
})(typeof window !== "undefined" ? window : this, function (window, noGlobal){
});

The jQuery code is contained in a self-executing function, and then returns an index pointing to jQuery, forming a closure. Using the jQuery object, you can access the methods defined in the self-executing function, but cannot access it outside, preventing The variable naming conflicts with the outside world. At the same time, the window object is passed into the function as a parameter. In the function, jQuery and $ are mounted on the window object object, so that the outside world can also directly access it through window.$ and window.jQuery jQuery object. Usually more $ is used, which actually refers to window.$, but the window object is usually omitted.

    if (!noGlobal) {
        window.jQuery = window.$ = jQuery; // 将 jQuery 和 $ 挂载到 window 对象对象上
    }
    return jQuery; // 然后返回出一个指向 jQuery 的索引

At the same time, in order to prevent conflicts between the pointing of $ in different libraries, jQuery can also restore the pointing of $ and jQuery to the original pointing, as long as the jQuery.noConflict method is used.

    var
        _jQuery = window.jQuery, // 保存 window.jQuery 的值
        _$ = window.$; // 保存 window.$ 的值
    jQuery.noConflict = function (deep) {
        if (window.$ === jQuery) {
            window.$ = _$;
        }
        if (deep && window.jQuery === jQuery) { // 根据参数判断是否还原 window.jQuery 的值
            window.jQuery = _jQuery;
        }
        return jQuery;
    };

First use jQuery and $ to save the original values ​​of window.jQuery and window.$, if you call the jQuery.noConflict method, judge the incoming parameters, if the parameter value is false, only release $, restore to the original value, if the parameter value If it is true, it will restore window.jQuery to its original value.

Overloading of jQuery functions

When jQuery is used, it can be used as a function to directly call $ and pass in parameters, or it can be used as an object to call the method of the object. As an object, we will discuss it later. Let’s talk about using $ as a function first.

Since the function of the same name in jQuery will be overwritten, when the incoming parameters are different, a function cannot be selected from multiple functions of the same name, and a unique function is selected according to the function name, so when the types of incoming parameters are different, it is necessary to Number, type and other information to determine the specific processing method. When calling jQuery, it points to a function.

jQuery = function (selector, context) {
    return new jQuery.fn.init(selector, context);
},

It will directly return an object with jQuery.fn.init as the constructor and new out. In the jQuery.fn.init function, different processing will be performed according to the different parameters passed in.

init = jQuery.fn.init = function (selector, context, root) {
        var match, elem;
        if (!selector) { // 如果第一个参数为空,直接 return 调用函数的对象
          return this;
        }
        root = root || rootjQuery;
        if (typeof selector === "string") {
            // 参数为字符串,进行处理
        } else if (selector.nodeType) {
            // 参数为元素节点,进行处理
        } else if (isFunction(selector)) {
            //参数为函数,进行处理
        }
        return jQuery.makeArray(selector, this);
      };
    init.prototype = jQuery.fn; // 将 init 函数的原型指定为 jQuery.fn,则 init 构造函数 new 出的对象就都可以直接使用 init 函数的原型也就是 jQuery.fn 包含的方法。

When the parameter is empty, the caller of the init function is returned, and finally, jQuery, the $ object, can be used, and the methods on the object can be used. When the first parameter is a string, it can be a selector, html code (a DOM element will be created and packaged into a jQuery object), when it is a DOM object, it will be packaged into a jQuery object, and when it is a function, it $(fn)is equivalent to $(document).ready(fn), it will be in After the page DOM is loaded, fn is called, which is better than window.onload in performance.

jQuery plugin

As mentioned above, jQuery can be used as an object to use its bound methods, such as the $.trim method, to remove spaces on both sides of a string. In addition, the prototype of the constructor init of the jQuery object points to jQuery.fn. After the DOM object is wrapped into a jQuery object, the methods of jQuery.fn, such as $('p').css method, can be called. Both of these methods can add new methods, corresponding to the two jQuery plugins.

Adding plugins uses the jQuery.extend function and jQuery.fn.extend, which actually point to the same function, but the caller of the function is different, and the this point is different.

The $.extend function itself can be used as a tool function to deal with the merging of objects, syntax jQuery.extend([deep], target, object1, [objectN]), this function will determine whether the first parameter is a Boolean value (optional), if so, perform a deep copy, if not, perform a shallow copy copy. Then, according to the number of other parameters except the Boolean value, it is judged whether to add a plug-in. If there are more than one remaining parameters, the first one will be used as the target, and the attributes of other objects will be copied to the target, and if there is only one parameter, The method of this parameter object will be added to the jQuery object, or jQuery.fn, depending on the object that calls the function. E.g:

:(function($) {
    $.fn.extend({ // 参数对象
        'color': function(){ // 对象的属性将会复制到 $.fn 上
            // 插件代码
        },
        'border': function () {
            // 插件代码
        }
    });
})(jQuery);

In the code of jQuery itself, the $.extend method is also used extensively. This method can be learned in contrast to Object.assign().

material:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325717077&siteId=291194637