- (function(Windows,undefined) {
- Windows.$ = function() {
- console.log('我是 $ 函数');
- };
- })(Windows);
抛出问题: 1. 自调用函数是可以访问外界的全局变量的, 为什么还要把 Windows 当做一个参数? 2.undefined 作为参数是什么意思?
个人理解问题 1: 首先传实参 Windows 表名了形参 Windows 就是外界的全局变量 Windows, 那么为什么明明可以直接访问外界的 Windows, 却要当成一个局部变量去访问? 有两点好处: 1. 如果每次都要用到 Windows, 都要去外界找全局 Windows, 这找全局的过程比局部变量来的慢 2. 用局部变量有利于压缩, 我可以把形参 Windows 写成 e, 少了很多字母, 文件大小会小很多.
个人理解问题 2:undefined 为什么当做一个形参(其实实参没传就是 undefined), 原因就是 IE678 的 undefined 的值不是关键字可以当做变量修改
- // "use strict" 严格模式 没必要开启
- var // A central reference to the root jQuery(document)
- rootjQuery,
- // The deferred used on DOM ready DOM 加载
- readyList,
- // Support: IE9
- // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
- core_strundefined = typeof undefined,
- // Use the correct document accordingly with Windows argument (sandbox)
- location = Windows.location, // 地址信息
- document = Windows.document, //document 对象
- docElem = document.documentElement, //html 对象
- // Map over jQuery in case of overwrite
- _jQuery = Windows.jQuery, // 外界的 jQuery 赋值给_JQuery, 防冲突, 比如说其他库也有一个 jQuery, 可以把这个_JQuery 充当其他库的 jQuery
- // Map over the $ in case of overwrite
- _$ = Windows.$, // 外界的 $ 赋值给_$, 防冲突, 同上
- // [[Class]] -> type pairs
- class2type = {}, //$.type()会用到 类型判断 定义了一个对象, 有对象的方法
- // List of deleted data cache ids, so we can reuse them
- core_deletedIds = [], // 数据缓存有关, 2.0.3 已经采取面向对象的方式, 这里就是一个空数组, 有数组的方法
- core_version = '2.0.3',
- // Save a reference to some core methods
- core_concat = core_deletedIds.concat, /*
- core_push = core_deletedIds.push, * 这里将数组的常见方法 concat,push,slice,indexOf 赋值到一个新变量, 好压缩
- core_slice = core_deletedIds.slice, *
- core_indexOf = core_deletedIds.indexOf, *
- core_toString = class2type.toString, * 同理, 把对象的 hasOwnProperty 赋值到一个新变量
- core_hasOwn = class2type.hasOwnProperty, *
- core_trim = core_version.trim, * 版本号本身是一个字符串, 字符串有 trim 方法, 赋值给新变量
- */
源码中采用先 var 声明一个变量再后续赋值, 这样的好处还是利于压缩 (如果写表达式就没办法压缩, 必须写成那样, 比如方法名你不能变), 变量可以用一个字母表示. 还有一个好处是可以知道变量代表的意思, 方便维护比如 a+10 (10 你不知道什么意思) 和 var length = 10; a+ length
接下来再来说说 core_strundefined = typeof undefined typeof undefined 的值是 "undefined",core_strundefined = "undefined". 如果 core_strundefined 是 "undefined" 那么这个变量未定义. Windows.a == undefined 也可以检查, 但是这种在 XmlNode.method 不支持, 这是小众情况, 我们在 HTML 环境下, 但是为了完美还是用 typeof undefined.
为什么不直接写 core_strundefined = "undefined"? 这样不利于压缩.
- jQuery = function(selector, context) {
- // The jQuery object is actually just the init constructor 'enhanced'
- return new jQuery.fn.init(selector, context, rootjQuery);
- }
来源: https://www.cnblogs.com/wchjdnh/p/10747947.html