简单剖析jQuery源码

HaoOuBa
2021-03-29 / 4 评论 / 457 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2021年04月02日,已超过1192天没有更新,若内容或图片失效,请留言反馈。
(function (global, factory) {
    /*
     *
     * CommonJS 规范
     * 用于执行传递进来的factory函数
     *
     */

    if (typeof module !== 'undefined' && typeof module.exports === 'object') {
        /*
         *
         * 当前是 nodejs 环境
         *
         */
        // ....
    } else {
        /*
         *
         * 当前是浏览器环境
         * 浏览器环境直接执行factory函数
         *
         */
        factory(global);
    }
})(typeof window !== 'undefined' ? window : this, function (window, noGlobal) {
    /*
     *
     * 返回一个jQuery出去
     * 使其能够链式操作
     *
     */
    jQuery = function (selector, context) {
        return new jQuery.fn.init(selector, context);
    };

    /*
     *
     * jQuery共有原型空间
     *
     */
    jQuery.fn = jQuery.prototype = {
        jquery: '1.0.0',

        constructor: jQuery,

        /*
         *
         * 将init返回出的对象改成数组
         *
         */
        splice: [].splice
    };

    init = jQuery.fn.init = function (selector) {
        var list = document.querySelectorAll(selector);
        [].push.apply(this, list);
    };

    /*
     *
     * init与jQuery共享同一个原型(空间)
     *
     */
    init.prototype = jQuery.fn;

    /*
     *
     * noGlobal不存在时
     * 表示当前环境是浏览器
     * 给window挂上$
     *
     */
    if (!noGlobal) {
        window.$ = window.jQuery = jQuery;
    }
    return jQuery;
});
10

评论 (4)

取消
  1. 头像
    hj
    Windows 10 · QQ Browser

    画图

    回复
  2. 头像
    hj
    Windows 10 · QQ Browser

    画图

    回复
  3. 头像
    遇上你
    Windows 10 · Google Chrome

    画图

    回复
    1. 头像
      易航
      Android · Google Chrome
      @ 遇上你

      脚本?

      回复