├── composer.phar ├── image ├── qrcode_for_gh_dd8cefdd6396_258.jpg ├── qrcode_for_gh_dd8cefdd6396_258.1.jpg └── de65e327-cca2-4593-90b9-5630363dde3e.png ├── underscore源码学习 ├── testapi │ ├── test.js │ └── test.html └── underscore注释版.js ├── backbone源码学习 └── testapi │ ├── test.js │ └── test.html ├── zepto源码学习 ├── testapi │ ├── test.html │ └── test.js └── zepto注释版.js └── README.md /composer.phar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JiayiLi/source-code-study/HEAD/composer.phar -------------------------------------------------------------------------------- /image/qrcode_for_gh_dd8cefdd6396_258.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JiayiLi/source-code-study/HEAD/image/qrcode_for_gh_dd8cefdd6396_258.jpg -------------------------------------------------------------------------------- /image/qrcode_for_gh_dd8cefdd6396_258.1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JiayiLi/source-code-study/HEAD/image/qrcode_for_gh_dd8cefdd6396_258.1.jpg -------------------------------------------------------------------------------- /image/de65e327-cca2-4593-90b9-5630363dde3e.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JiayiLi/source-code-study/HEAD/image/de65e327-cca2-4593-90b9-5630363dde3e.png -------------------------------------------------------------------------------- /underscore源码学习/testapi/test.js: -------------------------------------------------------------------------------- 1 | var func = function(greeting,haha){ console.log(haha);return greeting + ': ' + this.name }; 2 | func = _.bind(func, {name: 'moe'}, 'hi'); 3 | console.log(func("huhu")); 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /backbone源码学习/testapi/test.js: -------------------------------------------------------------------------------- 1 | // var test = Backbone.noConflict(); 2 | // console.log(test); 3 | console.log(Backbone); 4 | 5 | var localBackbone = Backbone.noConflict(); 6 | // var model = localBackbone.Model.extend(...); 7 | 8 | console.log(localBackbone); -------------------------------------------------------------------------------- /zepto源码学习/testapi/test.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Document 6 | 7 | 8 | 9 | 10 | 15 |

a paragraph

16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /underscore源码学习/testapi/test.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Document 6 | 7 | 8 | 9 | 10 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /backbone源码学习/testapi/test.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Document 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /zepto源码学习/testapi/test.js: -------------------------------------------------------------------------------- 1 | // var class2type = {}, 2 | // toString = class2type.toString; 3 | // $.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { 4 | // class2type[ "[object " + name + "]" ] = name.toLowerCase() 5 | // }) 6 | // function isFunction(value) { console.log(type(value)); 7 | // return type(value) == "function" } 8 | // function type(obj) { 9 | 10 | // return obj == null ? String(obj) : 11 | // class2type[toString.call(obj)] || "object" 12 | // } 13 | 14 | // var t = [1,2,3] 15 | 16 | // var c = isFunction(t); 17 | // console.log(c); 18 | 19 | 20 | // function Z(dom, selector) { 21 | // var i, len = dom ? dom.length : 0 22 | // console.log(dom); 23 | // for (i = 0; i < len; i++) this[i] = dom[i]; 24 | // this.length = len 25 | // this.selector = selector || '' 26 | // } 27 | 28 | // var t = new Z ($('li'),); 29 | // console.log(t.length); 30 | // var hZ = function(dom, selector) { 31 | // console.info(dom); 32 | // console.info(selector); 33 | // return new Z(dom, selector) 34 | // } 35 | // var isZ = function(object) { 36 | // console.log(object instanceof hZ); 37 | // return object instanceof hZ 38 | // } 39 | // 40 | 41 | 42 | var hei = { 43 | constructor:c, 44 | concat:function(){ 45 | console.log("concat"); 46 | } 47 | } 48 | var c = []; 49 | c.prototype = hei; 50 | 51 | 52 | 53 | console.log($("li").first()); 54 | console.log($.fn); 55 | console.log($.zepto.Z.prototype); 56 | 57 | 58 | // console.log(window); 59 | 60 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 源码学习 2 | 3 | > 项目结构,两种方式: 4 | > 1. 不在本项目中,引用项目地址 eg:node.js 之 module.js 5 | > 2. 在本项目中,eg:underscore.js 6 | > ![目录结构](image/de65e327-cca2-4593-90b9-5630363dde3e.png)
7 | 其中,testapi文件夹 为测试源码 API 所用,无实际意义。 8 | underscore注释版.js 为学习材料,有完整注释。 9 | 10 | 11 | 12 | 13 | ### `node.js 之 module.js` 14 | 项目地址 :[node.js-module](https://github.com/JiayiLi/node.js-module) 有完整注释;
15 | 系统知识梳理:[【 js 模块加载 】深入学习模块化加载(node.js 模块源码)](http://www.cnblogs.com/lijiayi/p/js_node_module.html) 16 | 17 | ### `underscore.js` 18 | **JavaScript 工具库** 19 | 20 | 知识点梳理: 21 | - [【 js 基础 】 深浅拷贝](http://www.cnblogs.com/lijiayi/p/jsdeeepcopy.html) 22 | - [【 js 性能优化】underscore throttle 与 debounce 节流](http://www.cnblogs.com/lijiayi/p/jsoptimise1.html) 23 | 24 | 看完 underscore 建议阅读书籍《javascript函数式编程》 25 | 26 | ### `zepto.js` 27 | **轻量级的针对现代高级浏览器的JavaScript库,与jquery有着类似的api** 28 | 29 | 知识点梳理: 30 | - [【 js 基础 】【 源码学习 】 setTimeout(fn, 0) 的作用](http://www.cnblogs.com/lijiayi/p/setTimeout0.html) 31 | 32 | 33 | 学习资料推荐: 34 | [zepto对象思想与源码分析](https://www.kancloud.cn/wangfupeng/zepto-design-srouce/173682) 35 | 36 | 37 | 38 | ### `backbone.js` 39 | **以类jq和underscore为基础的mvc框架** 40 | 知识点梳理: 41 | - [【 js 基础 】【 源码学习 】backbone 源码阅读(一)](http://www.cnblogs.com/lijiayi/p/backbone1.html) (1、MVC 框架 42 | 2、观察者模式 以及 控制反转) 43 | - [【 js 基础 】【 源码学习 】backbone 源码阅读(二)](http://www.cnblogs.com/lijiayi/p/backbone2.html) (1、控制反转、依赖注入) 44 | - [【 js 基础 】【 源码学习 】backbone 源码阅读(三)](http://www.cnblogs.com/lijiayi/p/backbone3.html) (浅谈 REST 和 CRUD) 45 | 46 | ------ 47 | 48 | 综合 以上: 49 | [【 js 基础 】【 源码学习 】源码设计 (zepto、underscore、backbone)](http://www.cnblogs.com/lijiayi/p/sourcecode.html) `更新了bacbone设计于8月12日` 50 | 51 | 52 | -------- 53 | 54 | ### advice 55 | - 邮箱: 56 | 57 | 58 | ### catch me 59 | - 知乎:[李佳怡](https://www.zhihu.com/people/jiayi-0526) 60 | - 知乎专栏:[李佳怡的纸糊](https://zhuanlan.zhihu.com/front-end-web) 专注于前端知识,学一点,就确保搞懂一点。 61 | - 博客园:[TristaLee](http://www.cnblogs.com/lijiayi/) 62 | - 公众号:佳怡所思(ljyFEer)是前端,也不只是前端。
63 | ![公众号二维码](image/qrcode_for_gh_dd8cefdd6396_258.jpg) 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /zepto源码学习/zepto注释版.js: -------------------------------------------------------------------------------- 1 | // Zepto.js 2 | // (c) 2010-2017 Thomas Fuchs 3 | // Zepto.js may be freely distributed under the MIT license. 4 | // 5 | // 内容引用于: 6 | // Zepto 源码全剖析 地址:https://zhangxiang958.github.io/2017/02/16/Zepto%20%E6%BA%90%E7%A0%81%E5%85%A8%E5%89%96%E6%9E%90/ 7 | // zepto对象思想与源码分析 地址:https://www.kancloud.cn/wangfupeng/zepto-design-srouce/173692 8 | // 以及英文原文注释翻译 9 | 10 | var Zepto = (function() { 11 | 12 | // 变量初始化 13 | var undefined, key, $, classList, emptyArray = [], concat = emptyArray.concat, filter = emptyArray.filter, slice = emptyArray.slice, 14 | document = window.document, 15 | elementDisplay = {}, classCache = {}, 16 | cssNumber = { 'column-count': 1, 'columns': 1, 'font-weight': 1, 'line-height': 1,'opacity': 1, 'z-index': 1, 'zoom': 1 }, 17 | 18 | // 检测正则 19 | // 取出html代码中第一个html标签(或注释),如取出

123

345

中的

20 | fragmentRE = /^\s*<(\w+|!)[^>]*>/, 21 | // 匹配非嵌套标签,如

就不会被匹配,注意?:用来关闭捕获 22 | // 可以匹配
,
,

23 | singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, 24 | 25 | // 匹配自闭合标签 26 | // 将

,替换为

,将

替换为

abc

(在 tagExpanderRE 中定义)的不替换 27 | tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, 28 | // body html 29 | rootNodeRE = /^(?:body|html)$/i, 30 | // 大写字母 31 | capitalRE = /([A-Z])/g, 32 | 33 | // special attributes that should be get/set via method calls 34 | // 应该通过方法调用来设置/获取的特殊属性 35 | methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'], 36 | 37 | adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ], 38 | table = document.createElement('table'), 39 | tableRow = document.createElement('tr'), 40 | // 指定特殊元素的 容器 41 | containers = { 42 | 'tr': document.createElement('tbody'), 43 | 'tbody': table, 'thead': table, 'tfoot': table, 44 | 'td': tableRow, 'th': tableRow, 45 | '*': document.createElement('div') 46 | }, 47 | // 匹配一个包括(字母、数组、下划线、-)的字符串 48 | simpleSelectorRE = /^[\w-]*$/, 49 | class2type = {}, 50 | toString = class2type.toString, 51 | zepto = {}, 52 | camelize, uniq, 53 | tempParent = document.createElement('div'), 54 | propMap = { 55 | 'tabindex': 'tabIndex', 56 | 'readonly': 'readOnly', 57 | 'for': 'htmlFor', 58 | 'class': 'className', 59 | 'maxlength': 'maxLength', 60 | 'cellspacing': 'cellSpacing', 61 | 'cellpadding': 'cellPadding', 62 | 'rowspan': 'rowSpan', 63 | 'colspan': 'colSpan', 64 | 'usemap': 'useMap', 65 | 'frameborder': 'frameBorder', 66 | 'contenteditable': 'contentEditable' 67 | }, 68 | // 判断是否是arr 69 | isArray = Array.isArray || 70 | function(object){ return object instanceof Array } 71 | 72 | // 判断 element 是否符合 selector 的要求 73 | zepto.matches = function(element, selector) { 74 | // 判断是否为dom元素节点,nodeType 属性 值为1; 75 | // 当值为2时,为属性节点。 76 | if (!selector || !element || element.nodeType !== 1) return false 77 | //
This is the element!
78 | // 84 | // 详细了解 85 | // https://developer.mozilla.org/zh-CN/docs/Web/API/Element/matches 86 | var matchesSelector = element.matches || element.webkitMatchesSelector || 87 | element.mozMatchesSelector || element.oMatchesSelector || 88 | element.matchesSelector 89 | if (matchesSelector) return matchesSelector.call(element, selector) 90 | // fall back to performing a selector: 91 | // 如果浏览器不支持 matchesSelector 92 | // 如果有父节点,temp = false. 93 | var match, parent = element.parentNode, temp = !parent 94 | // 如果没有父节点,则 将tempParent当作父节点 (tempParent 头部定义为div),然后将当前元素加入到这个div中 95 | if (temp) (parent = tempParent).appendChild(element) 96 | 97 | // ~按位取反运算符 98 | // 使用按位取反运算符原因: indexOf 返回-1 表示没有匹配,返回 >= 0 表示匹配, 99 | // 而 boolean(0) = false , 100 | // console.log(~-1); // 0 101 | // console.log(~0) // -1 102 | // console.log(~1) // -2 103 | // 这样如果没有找到该元素,都会返回 -1 经过 按位取反运算符 之后为 0 104 | // 当 match = 0 即 false 表示没有匹配 105 | // 当 match 等于其它值,即 true ,表示成功匹配 106 | match = ~zepto.qsa(parent, selector).indexOf(element) 107 | // 如果没有 父节点,就执行 tempParent 移除当前元素,因为前面把当前元素加入到这个tempParent中 108 | temp && tempParent.removeChild(element) 109 | 110 | // 返回~zepto.qsa的结果 111 | return match 112 | } 113 | 114 | // 在代码中部,执行了 115 | // $.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { 116 | // class2type[ "[object " + name + "]" ] = name.toLowerCase() 117 | // }) 118 | // 用来给 class2type 对象赋值 119 | // 120 | //type 用来判断类型 121 | function type(obj) { 122 | return obj == null ? String(obj) : 123 | [toString.call(obj)] || "object" 124 | } 125 | 126 | // 判断是否是函数 127 | function isFunction(value) { return type(value) == "function" } 128 | 129 | // 判断是否是 window对象(注意,w为小写)指当前的浏览器窗口,window对象的window属性指向自身。 130 | // 即 window.window === window 131 | function isWindow(obj) { return obj != null && obj == obj.window } 132 | 133 | // 判断是否是 document 对象 134 | // window.document.nodeType == 9 数字表示为9,常量表示为 DOCUMENT_NODE 135 | function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE } 136 | 137 | // 判断是否是 object 138 | function isObject(obj) { return type(obj) == "object" } 139 | 140 | // 判断是否是最基本的 object:Object.getPrototypeOf(obj) == Object.prototype 141 | // Object.getPrototypeOf() 方法返回指定对象的原型(即, 内部[[Prototype]]属性的值) 142 | // getPrototypeOf 和 prototype 的区别: 143 | // getPrototypeOf是个function,而 prototype 是个属性 144 | // eg: 145 | // function MyConstructor() {} 146 | // var obj = new MyConstructor() 147 | // Object.getPrototypeOf(obj) === Object.prototype // false 148 | // var t = {c:"heihei"}; 149 | // Object.getPrototypeOf(t) === Object.prototype // true 150 | function isPlainObject(obj) { 151 | return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype 152 | } 153 | // 判断是否是数组或者对象数组 154 | function likeArray(obj) { 155 | var length = !!obj && 'length' in obj && obj.length, 156 | type = $.type(obj) 157 | 158 | return 'function' != type && !isWindow(obj) && ( 159 | 'array' == type || length === 0 || 160 | (typeof length == 'number' && length > 0 && (length - 1) in obj) 161 | ) 162 | } 163 | 164 | // 筛选数组,踢出 null undefined 元素 165 | function compact(array) { return filter.call(array, function(item){ return item != null }) } 166 | // $.fn.concat 在下文中定义 167 | // $.fn = { 168 | // ...... 169 | // concat: function(){ 170 | // var i, value, args = [] 171 | // for (i = 0; i < arguments.length; i++) { 172 | // value = arguments[i] 173 | // args[i] = zepto.isZ(value) ? value.toArray() : value 174 | // } 175 | // return concat.apply(zepto.isZ(this) ? this.toArray() : this, args) 176 | // }, 177 | // ...... 178 | // } 179 | // 180 | // ??????? 181 | function flatten(array) { return array.length > 0 ? $.fn.concat.apply([], array) : array } 182 | 183 | // 用于 css 的 camalCase 转换,例如 background-color 转换为 backgroundColor 184 | camelize = function(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) } 185 | 186 | // 将 backgroundColor 转换为 background-color 格式 187 | function dasherize(str) { 188 | return str.replace(/::/g, '/') 189 | .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') 190 | .replace(/([a-z\d])([A-Z])/g, '$1_$2') 191 | .replace(/_/g, '-') 192 | .toLowerCase() 193 | } 194 | 195 | // 数组去重 eg:[1,1,2,3,3] 替换为 [1,2,3] 196 | uniq = function(array){ return filter.call(array, function(item, idx){ return array.indexOf(item) == idx }) } 197 | 198 | // classCache 存储的数据是这样的: 199 | // { 200 | // abc: /(^|\s)abc(\s|$)/, // 能匹配 'abc' 或 ' abc ' 或 ' abc' 或 'abc ' 201 | // xyz: /(^|\s)abc(\s|$)/, 202 | // ... 203 | // } 204 | function classRE(name) { 205 | return name in classCache ? 206 | classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)')) 207 | } 208 | 209 | // 传入一个 css 的 name 和 value,判断这个 value 是否需要增加 'px' 210 | function maybeAddPx(name, value) { 211 | //dasherize(name) 将 backgroundColor 转换为 background-color 格式 212 | return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value 213 | } 214 | 215 | // 获取一个元素的默认 display 样式值,可能的结果是:inline block inline-block table .... (none 转换为 block) 216 | function defaultDisplay(nodeName) { 217 | var element, display 218 | if (!elementDisplay[nodeName]) { 219 | // 如果 elementDisplay 对象中,没有存储 nodeName 的信息 220 | // 则新建一个 nodeName 元素,添加到 body 中 221 | element = document.createElement(nodeName) 222 | document.body.appendChild(element) 223 | // 获取它的默认的 display 样式信息 224 | // jQuery的CSS()方法,其底层运作就应用了getComputedStyle以及getPropertyValue方法 225 | // 具体了解:http://www.zhangxinxu.com/wordpress/2012/05/getcomputedstyle-js-getpropertyvalue-currentstyle/ 226 | // getComputedStyle是一个可以获取当前元素所有最终使用的CSS属性值 227 | // eg: var dom = document.getElementById("test"), 228 | // style = window.getComputedStyle(dom , ":after"); 229 | // getComputedStyle方法是只读的,只能获取样式,不能设置,两个参数,第二个参数“伪类”是必需的(如果不是伪类,设置为null 230 | // getPropertyValue方法可以获取CSS样式申明对象上的属性值(直接属性名称) 231 | display = getComputedStyle(element, '').getPropertyValue("display") 232 | // 接着马上移除元素 233 | element.parentNode.removeChild(element) 234 | // 如果是'none' 则换成 'block' 235 | display == "none" && (display = "block") 236 | 237 | // 存储 238 | elementDisplay[nodeName] = display 239 | } 240 | return elementDisplay[nodeName] 241 | } 242 | 243 | //返回一个元素的子元素,数组形式 244 | function children(element) { 245 | // 有些浏览器支持 elem.children 获取子元素,有些不支持 246 | return 'children' in element ? 247 | slice.call(element.children) : 248 | // 浏览器不支持 elem.children 只能通过 elem.childNodes 获取子元素,nodeType=1为dom元素节点 249 | // $.map 下文定义的 250 | $.map(element.childNodes, function(node){ if (node.nodeType == 1) return node }) 251 | } 252 | 253 | // 构造函数 ,在 zepto.Z 中被使用 254 | function Z(dom, selector) { 255 | var i, len = dom ? dom.length : 0 256 | for (i = 0; i < len; i++) this[i] = dom[i] 257 | this.length = len 258 | this.selector = selector || '' 259 | } 260 | 261 | // `$.zepto.fragment` takes a html string and an optional tag name 262 | // to generate DOM nodes from the given html string. 263 | // The generated DOM nodes are returned as an array. 264 | // This function can be overridden in plugins for example to make 265 | // it compatible with browsers that don't support the DOM fully. 266 | // `$.zepto.fragment`需要一个html字符串和一个可选标记名来生成dom 267 | // 产生的dom返回一个数组形式 268 | // 该功能可以被插件覆盖 269 | // 没有覆盖所有浏览器 270 | // 271 | // 参数: 272 | // html: 待处理的html字符串 273 | // name: 通过 name 可在 containers 中查找容器节点,如果不传入,取得的容器默认为 div 274 | // properties: 节点属性对象 275 | zepto.fragment = function(html, name, properties) { 276 | var dom, nodes, container 277 | 278 | // A special case optimization for a single tag 279 | // singleTagRE 头部定义正则 匹配非嵌套标签 280 | // RegExp.$1 表示正则中的第一个括号匹配的内容,在此即 (\w+)对应的tag名称。 281 | // RegExp.$1 在模式匹配期间找到的,所存储的最近的1个部分。只读。全局对象RegExp会在每次成功匹配一个带括号的分组时,将匹配成功的结果存储起来。每当产生一个带括号的成功匹配时,$1…$9 属性的值就被修改。 可以在一个正则表达式模式中指定任意多个带括号的子匹配,但只能存储最新的九个。 282 | // 283 | // 如果 html 是单标签,则直接用该标签创建元素 284 | if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1)) 285 | 286 | // 如果不是单标签 287 | if (!dom) { 288 | // replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。 289 | // 290 | // 如果有replace 方法 291 | // 将

,替换为

,将

替换为

abc

292 | if (html.replace) html = html.replace(tagExpanderRE, "<$1>") 293 | 294 | // 如果 name 未传入,则赋值为 html 的第一个标签 295 | // fragmentRE 头部定义正则 用于取出html代码中第一个html标签(或注释) 296 | if (name === undefined) name = fragmentRE.test(html) && RegExp.$1 297 | // containers 头部定义 298 | // 指定特殊元素的 容器 299 | // containers = { 300 | // 'tr': document.createElement('tbody'), 301 | // 'tbody': table, 'thead': table, 'tfoot': table, 302 | // 'td': tableRow, 'th': tableRow, 303 | // '*': document.createElement('div') 304 | // }, 305 | if (!(name in containers)) name = '*' 306 | 307 | // 生成容器 及其 子元素 308 | container = containers[name] 309 | container.innerHTML = '' + html // 转变为字符串的快捷方式 310 | // 遍历 container 的子元素(先转换为数组形式) 311 | // 返回赋值给dom的同时,将container中的每个子元素移除。 312 | dom = $.each(slice.call(container.childNodes), function(){ 313 | container.removeChild(this) 314 | }) 315 | } 316 | 317 | // isPlainObject 之前定义的方法 用于判断是否是最基本的 object 318 | if (isPlainObject(properties)) { 319 | // 先将dom转换为 zepto 对象 320 | nodes = $(dom) 321 | 322 | // methodAttributes 头部定义 methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'] 323 | // 满足 methodAttributes 的,通过调用Zepto的方法赋值,否则通过 nodes.attr(key, value) // 否则,通过属性复制 324 | $.each(properties, function(key, value) { 325 | if (methodAttributes.indexOf(key) > -1) nodes[key](value) 326 | else nodes.attr(key, value) 327 | }) 328 | } 329 | 330 | // 最终返回的dom可能有两种形式 331 | // 第一,如果 html 是单标签,则dom被复制为一个zepto对象 dom = $(document.createElement(RegExp.$1)) 332 | // 第二,如果 html 不是单标签,则dom被复制为一个DOM节点的数组 333 | return dom 334 | } 335 | 336 | // `$.zepto.Z` swaps out the prototype of the given `dom` array 337 | // of nodes with `$.fn` and thus supplying all the Zepto functions 338 | // to the array. This method can be overridden in plugins. 339 | // 返回的是函数 Z 的一个实例 340 | zepto.Z = function(dom, selector) { 341 | return new Z(dom, selector) 342 | } 343 | 344 | // `$.zepto.isZ` should return `true` if the given object is a Zepto 345 | // collection. This method can be overridden in plugins. 346 | // 判断 object 否是 zepto.Z 的实例 347 | zepto.isZ = function(object) { 348 | return object instanceof zepto.Z 349 | } 350 | 351 | // `$.zepto.init` is Zepto's counterpart to jQuery's `$.fn.init` and 352 | // takes a CSS selector and an optional context (and handles various 353 | // special cases). 354 | // This method can be overridden in plugins. 355 | zepto.init = function(selector, context) { 356 | var dom 357 | // If nothing given, return an empty Zepto collection 358 | // 未传参,返回空Zepto对象 359 | if (!selector) return zepto.Z() 360 | // Optimize for string selectors 361 | // selector是字符串 362 | else if (typeof selector == 'string') { 363 | // 字符串的情况,一般有两种: 364 | // 第一,一段 html 代码,旨在通过zepto生成dom对象 365 | // 第二,一段查询字符串,旨在通过zepto查找dom对象 366 | // 将查询结果存储到 dom 变量中 367 | // 有 context 则查找,没有context 则为生成dom 368 | 369 | 370 | //去前后空格 371 | selector = selector.trim() 372 | // If it's a html fragment, create nodes from it 373 | // Note: In both Chrome 21 and Firefox 15, DOM error 12 374 | // is thrown if the fragment doesn't begin with < 375 | if (selector[0] == '<' && fragmentRE.test(selector)) 376 | // RegExp.$1取出来的就是第一个标签名称,即正则中 (\w+|!) 对应的内容 377 | 378 | //调用zepto.fragment生成dom 379 | dom = zepto.fragment(selector, RegExp.$1, context), selector = null // 及时清空 selector 不妨碍下面的判断 380 | // If there's a context, create a collection on that context first, and select 381 | // nodes from there 382 | // 如果传递了上下文context,在上下文中查找元素 383 | else if (context !== undefined) return $(context).find(selector) 384 | // If it's a CSS selector, use it to select nodes. 385 | // 如果是css选择器,调用zepto.qsa进行查找 386 | else dom = zepto.qsa(document, selector) 387 | } 388 | // If a function is given, call it when the DOM is ready 389 | // 如果选择器是个 function ,则调用 ready()方法 390 | else if (isFunction(selector)) return $(document).ready(selector) 391 | // If a Zepto collection is given, just return it 392 | // 如果选择器本身就是 zepto 实例,则直接返回 393 | else if (zepto.isZ(selector)) return selector 394 | // 如果都不是 395 | else { 396 | // normalize array if an array of nodes is given 397 | // 如果给的是数组,则先筛选出数组中为 null和undefined的元素 398 | if (isArray(selector)) dom = compact(selector) 399 | // Wrap DOM nodes. 400 | // 如果是object,直接强制塞进一个数组 401 | else if (isObject(selector)) 402 | dom = [selector], selector = null 403 | // If it's a html fragment, create nodes from it 404 | // 如果是代码片段,调用zepto.fragment生成dom 405 | else if (fragmentRE.test(selector)) 406 | dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null // 及时清空 selector 不妨碍下面的判断 407 | // If there's a context, create a collection on that context first, and select 408 | // nodes from there 409 | // 如果传递了上下文context,在上下文中查找元素 410 | else if (context !== undefined) return $(context).find(selector) 411 | // And last but no least, if it's a CSS selector, use it to select nodes. 412 | // 如果是css选择器,调用zepto.qsa进行查找 413 | else dom = zepto.qsa(document, selector) 414 | } 415 | // create a new Zepto collection from the nodes found 416 | // 最终通过 zepto.Z 创建了对象 417 | return zepto.Z(dom, selector) 418 | } 419 | 420 | // `$` will be the base `Zepto` object. When calling this 421 | // function just call `$.zepto.init, which makes the implementation 422 | // details of selecting nodes and creating Zepto collections 423 | // patchable in plugins. 424 | // $(a) 返回 zepto 实例 425 | $ = function(selector, context){ 426 | return zepto.init(selector, context) 427 | } 428 | 429 | //内部方法:用户合并一个或多个对象到第一个对象 430 | //参数: 431 | // target 目标对象 对象都合并到target里 432 | // source 合并对象 433 | // deep 是否执行深度合并 434 | function extend(target, source, deep) { 435 | for (key in source) 436 | if (deep && (isPlainObject(source[key]) || isArray(source[key]))) { 437 | // source[key] 是对象,而 target[key] 不是对象, 则 target[key] = {} 初始化一下,否则递归会出错的 438 | if (isPlainObject(source[key]) && !isPlainObject(target[key])) 439 | target[key] = {} 440 | 441 | // source[key] 是数组,而 target[key] 不是数组,则 target[key] = [] 初始化一下,否则递归会出错的 442 | if (isArray(source[key]) && !isArray(target[key])) 443 | target[key] = [] 444 | // 执行递归 445 | extend(target[key], source[key], deep) 446 | } 447 | // 不满足以上条件,说明 source[key] 是一般的值类型,直接赋值给 target 就是了 448 | else if (source[key] !== undefined) target[key] = source[key] 449 | } 450 | 451 | // Copy all but undefined properties from one or more 452 | // objects to the `target` object. 453 | $.extend = function(target){ 454 | var deep, args = slice.call(arguments, 1) 455 | 456 | //第一个参数为boolean值时,表示是否深度合并 457 | if (typeof target == 'boolean') { 458 | deep = target 459 | //target取第二个参数 460 | target = args.shift() 461 | } 462 | // 遍历后面的参数,都合并到target上 463 | args.forEach(function(arg){ extend(target, arg, deep) }) 464 | return target 465 | } 466 | 467 | // `$.zepto.qsa` is Zepto's CSS selector implementation which 468 | // uses `document.querySelectorAll` and optimizes for some special cases, like `#id`. 469 | // This method can be overridden in plugins. 470 | // 471 | // 472 | // 通过选择器表达式查找DOM 473 | // 原理 判断下选择器的类型(id/class/标签/表达式) 474 | // 475 | // 当浏览器不支持 el.matches 时,可以用 document.querySelectorAll 来实现 matchs 476 | // https://developer.mozilla.org/zh-CN/docs/Web/API/Element/matches 477 | // 478 | // Zepto的css选择器,使用document.querySelectorAll 及优化处理一些特殊情况,可被插件覆盖 479 | zepto.qsa = function(element, selector){ 480 | var found, 481 | maybeID = selector[0] == '#', //如果有 # 就是id选择器 482 | maybeClass = !maybeID && selector[0] == '.', //不是id选择器&& 有 . ,是class选择器 483 | 484 | // 是如果是 id 或 class,则取符号后的名字,如果没有类和名字,则直接是selector 485 | // eg:selector = "#xixi"; selector.slice(1); 输出 "xixi" 486 | nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, // Ensure that a 1 char tag name still gets checked 487 | // simpleSelectorRE 用于匹配一个包括(字母、数组、下划线、-)的字符串, 是否是一个简单的字符串(可能是一个复杂的选择器,如 'div#div1 .item[link] .red') 488 | isSimple = simpleSelectorRE.test(nameOnly) 489 | 490 | // 以下代码的基本思路是: 491 | // 1. 优先通过 ID 获取元素; 492 | // 2. 然后试图通过 className 和 tagName 获取元素 493 | // 3. 最后通过 querySelectorAll 来获取 494 | 495 | // 判断是否有getElementById方法 && 是个单选择 && 是个id选择器 496 | return (element.getElementById && isSimple && maybeID) ? // Safari DocumentFragment doesn't have getElementById 497 | // 如果找到元素,则返回 [该元素],否则返回 []。 498 | ( (found = element.getElementById(nameOnly)) ? [found] : [] ) : 499 | //如果不满足判断条件,element既不是dom元素节点,也不是整个文档(DOM 树的根节点) #document,也不是 代表轻量级的 Document 对象,能够容纳文档的某个部分 #document 片段,那么就返回[]因为其他节点找不到元素 500 | (element.nodeType !== 1 && element.nodeType !== 9 && element.nodeType !== 11) ? [] : 501 | // 将获取的所有元素集合,都转换为数组 502 | slice.call( 503 | // 条件判断 A ? (B ? C : D) : E 504 | // 判断是否单选择, 不是 id 选择器, 有 getElementByClassName 方法 505 | isSimple && !maybeID && element.getElementsByClassName ? // DocumentFragment doesn't have getElementsByClassName/TagName 506 | maybeClass ? element.getElementsByClassName(nameOnly) : // If it's simple, it could be a class 507 | element.getElementsByTagName(selector) : // Or a tag 508 | element.querySelectorAll(selector) // Or it's not simple, and we need to query all 509 | ) 510 | } 511 | 512 | // 在元素集中过滤某些元素 513 | function filtered(nodes, selector) { 514 | // $.fn.filter 下文定义 515 | return selector == null ? $(nodes) : $(nodes).filter(selector) 516 | } 517 | 518 | // 父元素是否包含子元素 判断 parent 是否包含 node 519 | $.contains = document.documentElement.contains ? 520 | // 浏览器支持 contains 方法 521 | function(parent, node) { 522 | return parent !== node && parent.contains(node) 523 | } : 524 | // 不支持 contains 方法 525 | function(parent, node) { 526 | while (node && (node = node.parentNode)) 527 | if (node === parent) return true 528 | return false 529 | } 530 | 531 | // 处理 arg为函数/值 532 | // 为函数,返回函数返回值 533 | // 为值,返回值 534 | function funcArg(context, arg, idx, payload) { 535 | return isFunction(arg) ? arg.call(context, idx, payload) : arg 536 | } 537 | 538 | // 设置属性 539 | function setAttribute(node, name, value) { 540 | // 如果值为空,就移除这个属性,不然就设置值 541 | value == null ? node.removeAttribute(name) : node.setAttribute(name, value) 542 | } 543 | 544 | // access className property while respecting SVGAnimatedString 545 | // 对SVGAnimatedString的兼容 546 | function className(node, value){ 547 | var klass = node.className || '', 548 | svg = klass && klass.baseVal !== undefined 549 | 550 | if (value === undefined) return svg ? klass.baseVal : klass 551 | svg ? (klass.baseVal = value) : (node.className = value) 552 | } 553 | 554 | // "true" => true 555 | // "false" => false 556 | // "null" => null 557 | // "42" => 42 558 | // "42.5" => 42.5 559 | // "08" => "08" 560 | // JSON => parse if valid 561 | // String => self 562 | // 563 | // 序列化值 把自定义数据读出来时做应该的转换,将字符串变成相应的对象或者值 564 | function deserializeValue(value) { 565 | try { 566 | return value ? 567 | value == "true" || 568 | ( value == "false" ? false : 569 | value == "null" ? null : 570 | +value + "" == value ? +value : 571 | /^[\[\{]/.test(value) ? $.parseJSON(value) : 572 | value ) 573 | : value 574 | } catch(e) { 575 | return value 576 | } 577 | } 578 | 579 | // 将上文定义的函数,暴露给 $ 对象(其实 $ 是一个 function) 580 | $.type = type 581 | $.isFunction = isFunction 582 | $.isWindow = isWindow 583 | $.isArray = isArray 584 | $.isPlainObject = isPlainObject 585 | 586 | // 空对象 587 | $.isEmptyObject = function(obj) { 588 | var name 589 | for (name in obj) return false 590 | return true 591 | } 592 | 593 | //数字 594 | $.isNumeric = function(val) { 595 | var num = Number(val), type = typeof val 596 | return val != null && type != 'boolean' && 597 | (type != 'string' || val.length) && 598 | !isNaN(num) && isFinite(num) || false 599 | } 600 | 601 | // 获取在数组中的索引 602 | // 参数i 从第几个开始搜索 603 | $.inArray = function(elem, array, i){ 604 | return emptyArray.indexOf.call(array, elem, i) 605 | } 606 | 607 | //将字符串转成驼峰格式 608 | $.camelCase = camelize 609 | 610 | //去字符串头尾空格 611 | $.trim = function(str) { 612 | return str == null ? "" : String.prototype.trim.call(str) 613 | } 614 | 615 | // plugin compatibility 616 | $.uuid = 0 617 | $.support = { } 618 | $.expr = { } 619 | $.noop = function() {} 620 | 621 | // 针对 elements(对象数组或数组),对每个元素都经过 callback 函数的过滤,并将过滤通过的元素,push到一个新数组中,返回新数组 622 | $.map = function(elements, callback){ 623 | var value, values = [], i, key 624 | if (likeArray(elements)) 625 | for (i = 0; i < elements.length; i++) { 626 | value = callback(elements[i], i) 627 | if (value != null) values.push(value) 628 | } 629 | else 630 | for (key in elements) { 631 | value = callback(elements[key], key) 632 | if (value != null) values.push(value) 633 | } 634 | return flatten(values) 635 | } 636 | 637 | // 遍历 elements 所有元素(数组、对象数组、对象),执行 callback 方法,最终还是返回 elements 638 | // === false) return elements 一旦有函数返回 false,即跳出循环,类似 break 639 | $.each = function(elements, callback){ 640 | var i, key 641 | if (likeArray(elements)) { 642 | for (i = 0; i < elements.length; i++) 643 | if (callback.call(elements[i], i, elements[i]) === false) return elements 644 | } else { 645 | for (key in elements) 646 | if (callback.call(elements[key], key, elements[key]) === false) return elements 647 | } 648 | 649 | return elements 650 | } 651 | 652 | // 查找数组满足过滤函数的元素 653 | $.grep = function(elements, callback){ 654 | // 上文定义:filter = emptyArray.filter 655 | return filter.call(elements, callback) 656 | } 657 | 658 | 659 | if (window.JSON) $.parseJSON = JSON.parse 660 | 661 | // Populate the class2type map 662 | // 填充class2type的值 663 | $.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { 664 | class2type[ "[object " + name + "]" ] = name.toLowerCase() 665 | }) 666 | 667 | // Define methods that will be available on all 668 | // Zepto collections 669 | // 定义一些方法给 zepto 对象使用 670 | $.fn = { 671 | constructor: zepto.Z, 672 | length: 0, 673 | 674 | // Because a collection acts like an array 675 | // copy over these useful array functions 676 | // 因为一个 zepto 对象,本身就是一个数组,所以需要一些针对数组的方法 677 | forEach: emptyArray.forEach, 678 | reduce: emptyArray.reduce, 679 | push: emptyArray.push, 680 | sort: emptyArray.sort, 681 | splice: emptyArray.splice, 682 | indexOf: emptyArray.indexOf, 683 | // 合并多个数组 684 | concat: function(){ 685 | var i, value, args = [] 686 | for (i = 0; i < arguments.length; i++) { 687 | value = arguments[i] // value 是最后一个参数 688 | args[i] = zepto.isZ(value) ? value.toArray() : value 689 | } 690 | return concat.apply(zepto.isZ(this) ? this.toArray() : this, args) 691 | }, 692 | 693 | // `map` and `slice` in the jQuery API work differently 694 | // from their array counterparts 695 | // 遍历对象/数组 在每个元素上执行回调,将回调的返回值放入一个新的Zepto返回 696 | map: function(fn){ 697 | // $.map 返回的是一个数组 698 | // 再用 $ 封装返回 699 | return $($.map(this, function(el, i){ return fn.call(el, i, el) })) 700 | }, 701 | // 对原生的 Array slice 包装(数组选取方法) 702 | slice: function(){ 703 | // 直接数组的slice方法,并将结果用 $ 封装返回 704 | return $(slice.apply(this, arguments)) 705 | }, 706 | // 当DOM载入就绪时,绑定回调 707 | ready: function(callback){ 708 | // don't use "interactive" on IE <= 10 (it can fired premature) 709 | // 710 | // document.readyState:当document文档正在加载时,返回"loading"。当文档结束渲染但在加载内嵌资源时,返回"interactive",并引发DOMContentLoaded事件。当文档加载完成时,返回"complete",并引发load事件。 711 | // document.documentElement.doScroll:IE有个特有的方法doScroll可以检测DOM是否加载完成。 当页面未加载完成时,该方法会报错,直到doScroll不再报错时,就代表DOM加载完成了 712 | // 713 | // 关于 setTimeout(fn ,0) 的作用 可以参考文章:http://www.cnblogs.com/silin6/p/4333999.html 714 | if (document.readyState === "complete" || 715 | (document.readyState !== "loading" && !document.documentElement.doScroll)) 716 | setTimeout(function(){ callback($) }, 0) 717 | else { 718 | // 监听移除事件 719 | var handler = function() { 720 | document.removeEventListener("DOMContentLoaded", handler, false) 721 | window.removeEventListener("load", handler, false) 722 | callback($) 723 | } 724 | document.addEventListener("DOMContentLoaded", handler, false) 725 | window.addEventListener("load", handler, false) 726 | } 727 | return this 728 | }, 729 | 730 | // 取Zepto中指定索引的值 731 | // 获得整个数组或者是数组中的单个元素,未传参数,直接返回一整个数组,有参数,则试图返回单个元素(大于0,小于0 两种情况) 732 | get: function(idx){ 733 | return idx === undefined ? slice.call(this) : this[idx >= 0 ? idx : idx + this.length] 734 | }, 735 | // 将对象转化为数组 736 | // 原理是 伪数组转换成数组oa = {0:'a',length:1};Array.prototype.slice.call(oa); //["a"] 737 | toArray: function(){ return this.get() }, 738 | //获取集合长度 739 | size: function(){ 740 | return this.length 741 | }, 742 | // 将元素从这个DOM树中移除 743 | remove: function(){ 744 | return this.each(function(){ 745 | if (this.parentNode != null) 746 | this.parentNode.removeChild(this) 747 | }) 748 | }, 749 | // 用来遍历zepto集合,直到callback函数返回false为止 750 | each: function(callback){ 751 | // 原生 every 接收一个函数,如果返回 false 就停止循环, 752 | // every 与 map, some, forEach, filter 区别 753 | // every 就是每个都, filter 选出符合条件的, some 是只要有, forEach 是每一个都要做某事, map 是每个做完某事后排队 754 | emptyArray.every.call(this, function(el, idx){ 755 | return callback.call(el, idx, el) !== false 756 | }) 757 | // 最后返回本身对象 758 | return this 759 | }, 760 | // 过滤zepto对象,可以接受字符串或者函数 761 | // 在函数情况下,通过not函数过滤出selector函数返回值不为真的元素集合,再对这个集合过滤一下,得到selector函数为真的情况下的集合。 762 | // 字符串情况下,使用之前说明过的zepto.matches函数来判断。 763 | filter: function(selector){ 764 | if (isFunction(selector)) return this.not(this.not(selector)) 765 | return $(filter.call(this, function(element){ 766 | return zepto.matches(element, selector) 767 | })) 768 | }, 769 | // 在某个元素集合中添加元素 770 | // $('div') 可能只有三个 div 节点,那么 $('div').add('p') 再三个 div 节点的基础上,增加三个 p 节点 771 | add: function(selector,context){ 772 | // uniq函数——数组去重,例如:用来将 [1,1,2,2,3,3] 替换为 [1,2,3] 773 | return $(uniq(this.concat($(selector,context)))) 774 | }, 775 | // 判断数组中的第一个元素是不是符合selector 776 | is: function(selector){ 777 | return this.length > 0 && zepto.matches(this[0], selector) 778 | }, 779 | //排除集合里满足条件的记录 780 | //selector是函数时对函数返回值取反,获取不匹配的元素并放在数组中。 781 | //字符串情况下,先获取符合该选取器的元素,之后用indexOf函数取反。 782 | //类数组与NodeList的情况下,前者返回一个数组,后者返回一个zepto集合,之后再用indexOf函数取反。 783 | not: function(selector){ 784 | var nodes=[] 785 | // 如果是selector是function 786 | if (isFunction(selector) && selector.call !== undefined) 787 | this.each(function(idx){ 788 | if (!selector.call(this,idx)) nodes.push(this) 789 | }) 790 | else { 791 | var excludes = typeof selector == 'string' ? this.filter(selector) : 792 | (likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) : $(selector) 793 | this.forEach(function(el){ 794 | //如果 excludes 不包含数组中的元素,则将这个不包含在内的元素加入到 nodes 中 795 | if (excludes.indexOf(el) < 0) nodes.push(el) 796 | }) 797 | } 798 | //返回 nodes 799 | return $(nodes) 800 | }, 801 | // 判断当前对象集合的子元素是否有符合选择器的元素,或者是否包含指定的DOM节点,如果有,则返回新的对象集合 802 | has: function(selector){ 803 | return this.filter(function(){ 804 | return isObject(selector) ? 805 | $.contains(this, selector) : 806 | $(this).find(selector).size() 807 | }) 808 | }, 809 | // 取出指定index的元素 810 | eq: function(idx){ 811 | return idx === -1 ? this.slice(idx) : this.slice(idx, + idx + 1) 812 | }, 813 | // 取第一条$(元素) 814 | first: function(){ 815 | var el = this[0] 816 | return el && !isObject(el) ? el : $(el) 817 | }, 818 | // 取最后一条$(元素) 819 | last: function(){ 820 | var el = this[this.length - 1] 821 | return el && !isObject(el) ? el : $(el) 822 | }, 823 | // 用来在当前zepto集合里筛选出新的zepto集合。 824 | // 在selector是对象的情况下(指元素节点)先获取selector匹配的zepto集合,之后对这个集合进行filter操作,将每个元素和调用find函数的zepto集合进行匹配,只要这个集合中的元素能在调用find方法中的zepto集合中找到,则过滤成功,并过滤下一个。 825 | // selector是选择器时,通过map函数和zepto.qsa搜寻。 826 | find: function(selector){ 827 | var result, $this = this 828 | if (!selector) result = $() 829 | // 如果selector是对象 830 | else if (typeof selector == 'object') 831 | result = $(selector).filter(function(){ 832 | var node = this 833 | return emptyArray.some.call($this, function(parent){ 834 | return $.contains(parent, node) 835 | }) 836 | }) 837 | // 如果只有一个元素,则使用 qsa 判断,结果经过 $ 封装后赋值给 result 838 | else if (this.length == 1) result = $(zepto.qsa(this[0], selector)) 839 | // 如果有多个元素,则使用 map 遍历所有元素,使用 qsa 针对每个元素判断,符合条件即返回(map将返回包含符合条件的元素的新数组,并 $ 封装,支持链式操作!!) 840 | else result = this.map(function(){ return zepto.qsa(this, selector) }) 841 | return result 842 | }, 843 | // 从元素本身开始,逐级向上级元素匹配,并返回最先匹配selector的元素 844 | closest: function(selector, context){ 845 | var nodes = [], collection = typeof selector == 'object' && $(selector) 846 | this.each(function(_, node){ 847 | // 使用了while循环来不断往祖先方向移动。 848 | while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector))) 849 | //当node 不是context,document的时候,取node.parentNode 850 | node = node !== context && !isDocument(node) && node.parentNode 851 | 852 | if (node && nodes.indexOf(node) < 0) nodes.push(node) 853 | }) 854 | return $(nodes) 855 | }, 856 | // 取得所有匹配的祖先元素 $('h1').parents() => [, , ] 857 | parents: function(selector){ 858 | var ancestors = [], nodes = this 859 | // 取得所有祖先元素 860 | while (nodes.length > 0) 861 | nodes = $.map(nodes, function(node){ 862 | // 不能是 document,结果中元素不能重复。否则不执行push 863 | if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < 0) { 864 | ancestors.push(node) 865 | return node 866 | } 867 | }) 868 | // 筛选出符合selector的祖先元素 869 | return filtered(ancestors, selector) 870 | }, 871 | // 用来返回由zepto元素的父元素组成的zepto集合 872 | parent: function(selector){ 873 | // pluck方法,这个方法用来获取一个zepto集合中每个元素的某个属性值组成的zepto集合 874 | return filtered(uniq(this.pluck('parentNode')), selector) 875 | }, 876 | // 获得每个匹配元素集合元素的直接子元素,可通过 selector 过滤 877 | children: function(selector){ 878 | return filtered(this.map(function(){ return children(this) }), selector) 879 | }, 880 | // 获得每个匹配元素集合元素的子元素,包括文字和注释节点 881 | contents: function() { 882 | // 对于frame,则获取它的contentDocument属性,contentDocument返回这个窗体的文档节点。 883 | return this.map(function() { return this.contentDocument || slice.call(this.childNodes) }) 884 | }, 885 | // 获取对象集合中所有元素的兄弟节点,可通过 selector 过滤 886 | siblings: function(selector){ 887 | return filtered(this.map(function(i, el){ 888 | //使用 el.parentNode, 过滤出 el.parentNode 的子元素, 但是不包括 this 中的元素 889 | return filter.call(children(el.parentNode), function(child){ return child!==el }) 890 | }), selector) 891 | }, 892 | // 移除所有子元素 893 | empty: function(){ 894 | return this.each(function(){ this.innerHTML = '' }) 895 | }, 896 | // `pluck` is borrowed from Prototype.js 897 | // 返回集合中每个元素的某个属性 898 | pluck: function(property){ 899 | return $.map(this, function(el){ return el[property] }) 900 | }, 901 | // 用来让元素显示(还原成“默认样式”) 902 | // show 方法是为了显示对象,而对象隐藏的方式有两种:内联样式 或 css样式 903 | // this.style.display 只能获取内联样式的值(获取属性值) 904 | // getComputedStyle(this, '').getPropertyValue("display") 可以获取内联、css样式的值(获取 renderTree 的值) 905 | show: function(){ 906 | return this.each(function(){ 907 | //针对内联样式, 如果 display 为 none ,则替换成 '' 908 | this.style.display == "none" && (this.style.display = '') 909 | // 针对css样式,如果是 none 则修改为默认的显示样式 910 | if (getComputedStyle(this, '').getPropertyValue("display") == "none") 911 | this.style.display = defaultDisplay(this.nodeName) 912 | }) 913 | }, 914 | // 替换 915 | replaceWith: function(newContent){ 916 | // 先在前面插入,然后将当前对象移除 917 | return this.before(newContent).remove() 918 | }, 919 | // 匹配的每条元素都被单个元素包裹 920 | wrap: function(structure){ 921 | var func = isFunction(structure) 922 | //如果structure是字符串 923 | if (this[0] && !func) 924 | //直接转成DOM 925 | var dom = $(structure).get(0), 926 | clone = dom.parentNode || this.length > 1 //如果DOM已存在(通过在文档中读parentNode判断),或$集不止一条,需要克隆。避免DOM被移动位置 927 | 928 | return this.each(function(index){ 929 | // 调用了 wrapAll 930 | $(this).wrapAll( 931 | func ? structure.call(this, index) : 932 | clone ? dom.cloneNode(true) : dom 933 | ) 934 | }) 935 | }, 936 | // 用来将zepto集合中的元素包裹在一个html片段或者DOM元素中 937 | wrapAll: function(structure){ 938 | if (this[0]) { 939 | // 先在集合中的第一个元素前插入structure生成的元素 940 | $(this[0]).before(structure = $(structure)) 941 | var children 942 | // drill down to the inmost element 943 | // 遍历这个元素获取它的最内层DOM 944 | while ((children = structure.children()).length) structure = children.first() 945 | // 之后使用zepto原型中的append方法将zepto集合中的元素移动到刚刚获取的最里层元素中。 946 | $(structure).append(this) 947 | } 948 | return this 949 | }, 950 | // 将zepto集合中的每个元素的后代节点包裹起来 951 | wrapInner: function(structure){ 952 | var func = isFunction(structure) 953 | return this.each(function(index){ 954 | // contents 获取zepto集合中某个元素的后代节点 955 | var self = $(this), contents = self.contents(), 956 | dom = func ? structure.call(this, index) : structure 957 | // 如果后代节点存在则使用wrapAll方法将它包裹,否则直接插入structure 958 | contents.length ? contents.wrapAll(dom) : self.append(dom) 959 | }) 960 | }, 961 | // 移除包裹结构 962 | unwrap: function(){ 963 | // 是遍历zepto集合中的父元素,将它们替换成它们的后代节点 964 | this.parent().each(function(){ 965 | $(this).replaceWith($(this).children()) 966 | }) 967 | return this 968 | }, 969 | // 将zepto集合中的元素克隆一份 970 | clone: function(){ 971 | // Node.cloneNode():Node将要被克隆的节点 ,该方法返回调用该方法的节点的一个副本. 972 | return this.map(function(){ return this.cloneNode(true) }) 973 | }, 974 | // 让集合元素不显示 975 | hide: function(){ 976 | return this.css("display", "none") 977 | }, 978 | // 切换显示和隐藏,参数setting为真时将zepto集合显示,反之隐藏。 979 | toggle: function(setting){ 980 | return this.each(function(){ 981 | var el = $(this) 982 | ;(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide() 983 | }) 984 | }, 985 | // 获取集合中每个元素的上一个元素放回新的zepto集合 986 | // previousElementSibling 返回当前元素在其父元素的子元素节点中的前一个元素节点,如果该元素已经是第一个元素节点,则返回null,该属性是只读的. 987 | prev: function(selector){ return $(this.pluck('previousElementSibling')).filter(selector || '*') }, 988 | // 获取集合中每个元素的下一个元素放回新的zepto集合 989 | // nextElementSibling 返回当前元素在其父元素的子元素节点中的后一个元素节点,如果该元素已经是最后一个元素节点,则返回null,该属性是只读的. 990 | next: function(selector){ return $(this.pluck('nextElementSibling')).filter(selector || '*') }, 991 | // 读写元素HTML内容 通过innerHTML读内容,append()写内容 992 | // 传参遍历执行写入 993 | // 未传参执行读 994 | html: function(html){ 995 | // 0 in arguments判断是否有参数 996 | return 0 in arguments ? 997 | this.each(function(idx){ 998 | var originHtml = this.innerHTML //记录原始的innerHTMl 999 | //如果参数html是字符串直接插入到记录中, 1000 | //如果是函数,则将当前记录作为上下文,调用该函数,且传入该记录的索引和原始innerHTML作为参数 1001 | $(this).empty().append( funcArg(this, html, idx, originHtml) ) 1002 | }) : 1003 | (0 in this ? this[0].innerHTML : null) 1004 | }, 1005 | // 读写元素文本内容,通过 textContent 读写文本, Node.textContent 属性表示一个节点及其后代的文本内容。 1006 | // 传参遍历执行写入 1007 | // 未传参执行读 1008 | text: function(text){ 1009 | // 0 in arguments判断是否有参数 1010 | return 0 in arguments ? 1011 | this.each(function(idx){ 1012 | var newText = funcArg(this, text, idx, this.textContent) 1013 | this.textContent = newText == null ? '' : ''+newText 1014 | }) : 1015 | (0 in this ? this.pluck('textContent').join("") : null) 1016 | }, 1017 | // 元素的HTML属性读写 1018 | // 仅有name,且为字符串时,表示读 1019 | attr: function(name, value){ 1020 | var result 1021 | return (typeof name == 'string' && !(1 in arguments)) ? 1022 | (0 in this && this[0].nodeType == 1 && (result = this[0].getAttribute(name)) != null ? result : undefined) : 1023 | this.each(function(idx){ 1024 | // 如果不是一个 元素 节点 则直接 return 1025 | if (this.nodeType !== 1) return 1026 | if (isObject(name)) for (key in name) setAttribute(this, key, name[key]) 1027 | else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name))) 1028 | }) 1029 | }, 1030 | // 移除属性 1031 | removeAttr: function(name){ 1032 | return this.each(function(){ this.nodeType === 1 && name.split(' ').forEach(function(attribute){ 1033 | setAttribute(this, attribute) 1034 | }, this)}) 1035 | }, 1036 | // 元素的DOM属性读写 1037 | // 有value,遍历写入 1038 | prop: function(name, value){ 1039 | //优先读取修正属性,DOM的两字母属性都是驼峰格式 1040 | name = propMap[name] || name 1041 | return (1 in arguments) ? 1042 | this.each(function(idx){ 1043 | this[name] = funcArg(this, value, idx, this[name]) 1044 | }) : 1045 | (this[0] && this[0][name]) 1046 | }, 1047 | // 删除属性 1048 | removeProp: function(name){ 1049 | name = propMap[name] || name 1050 | // delete 操作符能删除对象的某个属性 1051 | return this.each(function(){ delete this[name] }) 1052 | }, 1053 | // 用来获取和添加元素的“数据”,前面加上 'data-' 通过 attr 设置或者读取 1054 | data: function(name, value){ 1055 | var attrName = 'data-' + name.replace(capitalRE, '-$1').toLowerCase() 1056 | 1057 | var data = (1 in arguments) ? 1058 | this.attr(attrName, value) : 1059 | this.attr(attrName) 1060 | 1061 | return data !== null ? deserializeValue(data) : undefined 1062 | }, 1063 | // 用于设置和获取元素的value属性 1064 | val: function(value){ 1065 | if (0 in arguments) { 1066 | if (value == null) value = "" 1067 | return this.each(function(idx){ 1068 | this.value = funcArg(this, value, idx, this.value) 1069 | }) 1070 | } else { 1071 | // 在查询的情况下,如果是select元素并且带有multiple属性,则将它被选中的option子元素筛选出来并通过pluck方法一并获取它们的value属性 1072 | return this[0] && (this[0].multiple ? 1073 | $(this[0]).find('option').filter(function(){ return this.selected }).pluck('value') : 1074 | this[0].value) 1075 | } 1076 | }, 1077 | // 用来读写元素的位置与大小信息 1078 | offset: function(coordinates){ 1079 | // 如果有 coordinates 参数,设置坐标值,并返回当前对象 1080 | // 遍历每个元素,获取它的父元素的offset属性,之后将要设置的偏移位置减去父元素的偏移位置就能得到实际应该设置的left与top属性 1081 | if (coordinates) return this.each(function(index){ 1082 | var $this = $(this), 1083 | coords = funcArg(this, coordinates, index, $this.offset()), 1084 | parentOffset = $this.offsetParent().offset(), 1085 | props = { 1086 | top: coords.top - parentOffset.top, 1087 | left: coords.left - parentOffset.left 1088 | } 1089 | // position static时,设置 top、left是无效的 1090 | if ($this.css('position') == 'static') props['position'] = 'relative' 1091 | // 通过 css 赋值 1092 | $this.css(props) 1093 | }) 1094 | // 当前对象是空,则返回 null 1095 | if (!this.length) return null 1096 | // 如果元素尚未在DOM中则返回“{top:0,left:0}” 1097 | // Document.documentElement 是一个会返回文档对象(document)的根元素的只读属性(如HTML文档的 元素)。 1098 | if (document.documentElement !== this[0] && !$.contains(document.documentElement, this[0])) 1099 | return {top: 0, left: 0} 1100 | // Element.getBoundingClientRect()方法返回元素的大小及其相对于视口的位置。 1101 | var obj = this[0].getBoundingClientRect() 1102 | // window.pageXOffset 和 window.pageYOffset 可获取网页滚动的距离, 1103 | return { 1104 | left: obj.left + window.pageXOffset, 1105 | top: obj.top + window.pageYOffset, 1106 | width: Math.round(obj.width), 1107 | height: Math.round(obj.height) 1108 | } 1109 | }, 1110 | // 设置、获取 css 1111 | css: function(property, value){ 1112 | // 获取css 1113 | if (arguments.length < 2) { 1114 | // 获取第一个元素 1115 | var element = this[0] 1116 | if (typeof property == 'string') { 1117 | // 如果第一个无元素,直接返回。否则继续 1118 | if (!element) return 1119 | // 先从elem内联样式获取(element.style),此时需要 camelize(property) 转换,如将 background-color 变为 backgroundColor,如果未找到,则从css样式获取 computedStyle.getPropertyValue(property) 1120 | return element.style[camelize(property)] || getComputedStyle(element, '').getPropertyValue(property) 1121 | // 参数为数组 1122 | } else if (isArray(property)) { 1123 | if (!element) return 1124 | var props = {} 1125 | var computedStyle = getComputedStyle(element, '') 1126 | $.each(property, function(_, prop){ 1127 | props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop)) 1128 | }) 1129 | return props 1130 | } 1131 | } 1132 | 1133 | // 设置属性 1134 | var css = '' 1135 | if (type(property) == 'string') { 1136 | // 如果value参数是 '' null undefined 则移除这个css样式 1137 | if (!value && value !== 0) 1138 | this.each(function(){ this.style.removeProperty(dasherize(property)) }) 1139 | else 1140 | // maybeAddPx(property, value) 需要增加 px 的增加上 1141 | css = dasherize(property) + ":" + maybeAddPx(property, value) 1142 | // property 是对象的情况 1143 | } else { 1144 | for (key in property) 1145 | if (!property[key] && property[key] !== 0) 1146 | this.each(function(){ this.style.removeProperty(dasherize(key)) }) 1147 | else 1148 | css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';' 1149 | } 1150 | 1151 | return this.each(function(){ this.style.cssText += ';' + css }) 1152 | }, 1153 | // 获取一个元素的索引值 1154 | index: function(element){ 1155 | //这里的$(element)[0]是为了将字符串转成node,因为this是个包含node的数组 1156 | return element ? this.indexOf($(element)[0]) : this.parent().children().indexOf(this[0]) 1157 | }, 1158 | // 是否含有指定的类样式 1159 | hasClass: function(name){ 1160 | if (!name) return false 1161 | //some ES5的新方法 有一个匹配,即返回true 1162 | return emptyArray.some.call(this, function(el){ 1163 | return this.test(className(el)) 1164 | }, classRE(name)) 1165 | }, 1166 | // 增加一个或多个类名 1167 | addClass: function(name){ 1168 | if (!name) return this 1169 | return this.each(function(idx){ 1170 | if (!('className' in this)) return 1171 | classList = [] 1172 | var cls = className(this), newName = funcArg(this, name, idx, cls) 1173 | newName.split(/\s+/g).forEach(function(klass){ 1174 | if (!$(this).hasClass(klass)) classList.push(klass) 1175 | }, this) 1176 | classList.length && className(this, cls + (cls ? " " : "") + classList.join(" ")) 1177 | }) 1178 | }, 1179 | // 删除一个或多个类名 1180 | removeClass: function(name){ 1181 | return this.each(function(idx){ 1182 | if (!('className' in this)) return 1183 | if (name === undefined) return className(this, '') 1184 | classList = className(this) 1185 | funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass){ 1186 | //替换删除 1187 | classList = classList.replace(classRE(klass), " ") 1188 | }) 1189 | className(this, classList.trim()) 1190 | }) 1191 | }, 1192 | // 切换类的添加或移除 1193 | // 如果 when === true 则单纯执行 addClass 1194 | // 如果 when === false 则单纯执行 removeClass 1195 | toggleClass: function(name, when){ 1196 | if (!name) return this 1197 | return this.each(function(idx){ 1198 | var $this = $(this), names = funcArg(this, name, idx, className(this)) 1199 | names.split(/\s+/g).forEach(function(klass){ 1200 | (when === undefined ? !$this.hasClass(klass) : when) ? 1201 | $this.addClass(klass) : $this.removeClass(klass) 1202 | }) 1203 | }) 1204 | }, 1205 | // 读写元素 滚动条的垂直偏移 1206 | scrollTop: function(value){ 1207 | if (!this.length) return 1208 | var hasScrollTop = 'scrollTop' in this[0] 1209 | // 读 1210 | if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset 1211 | // 写 1212 | return this.each(hasScrollTop ? 1213 | function(){ this.scrollTop = value } : 1214 | function(){ this.scrollTo(this.scrollX, value) }) 1215 | }, 1216 | // 读写元素 滚动条的垂直偏移 1217 | scrollLeft: function(value){ 1218 | if (!this.length) return 1219 | var hasScrollLeft = 'scrollLeft' in this[0] 1220 | if (value === undefined) return hasScrollLeft ? this[0].scrollLeft : this[0].pageXOffset 1221 | return this.each(hasScrollLeft ? 1222 | function(){ this.scrollLeft = value } : 1223 | function(){ this.scrollTo(value, this.scrollY) }) 1224 | }, 1225 | // 返回集合中第一个元素的相对于定位元素的偏移 1226 | position: function() { 1227 | if (!this.length) return 1228 | 1229 | var elem = this[0], 1230 | // Get *real* offsetParent 1231 | // 找到第一个定位过的祖先元素 1232 | // HTMLElement.offsetParent 是一个只读属性,返回一个指向最近的(closest,指包含层级上的最近)包含该元素的定位元素。 1233 | offsetParent = this.offsetParent(), 1234 | // Get correct offsets 1235 | // 获取自身的offset 1236 | offset = this.offset(), 1237 | // 获取父元素的坐标 1238 | parentOffset = rootNodeRE.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset() 1239 | 1240 | // Subtract element margins 1241 | // note: when an element has margin: auto the offsetLeft and marginLeft 1242 | // are the same in Safari causing offset.left to incorrectly be 0 1243 | // 坐标减去外边框 margin 宽度 1244 | offset.top -= parseFloat( $(elem).css('margin-top') ) || 0 1245 | offset.left -= parseFloat( $(elem).css('margin-left') ) || 0 1246 | 1247 | // Add offsetParent borders 1248 | // 加上父元素的border 1249 | parentOffset.top += parseFloat( $(offsetParent[0]).css('border-top-width') ) || 0 1250 | parentOffset.left += parseFloat( $(offsetParent[0]).css('border-left-width') ) || 0 1251 | 1252 | // Subtract the two offsets 1253 | return { 1254 | top: offset.top - parentOffset.top, 1255 | left: offset.left - parentOffset.left 1256 | } 1257 | }, 1258 | // 返回第一个匹配元素用于定位的祖先元素 1259 | offsetParent: function() { 1260 | return this.map(function(){ 1261 | var parent = this.offsetParent || document.body 1262 | // 如果找到的定位元素 position=‘static’则继续往上找,直到body/Html 1263 | while (parent && !rootNodeRE.test(parent.nodeName) && $(parent).css("position") == "static") 1264 | parent = parent.offsetParent 1265 | return parent 1266 | }) 1267 | } 1268 | } 1269 | 1270 | // for now 1271 | // 给remove方法添加一个别名 1272 | $.fn.detach = $.fn.remove 1273 | 1274 | // Generate the `width` and `height` functions 1275 | // 在原型上添加width和height方法 1276 | ;['width', 'height'].forEach(function(dimension){ 1277 | //将width,hegiht转成Width,Height,用于document获取 1278 | var dimensionProperty = 1279 | dimension.replace(/./, function(m){ return m[0].toUpperCase() }) 1280 | 1281 | $.fn[dimension] = function(value){ 1282 | var offset, el = this[0] 1283 | //读时,是window 用innerWidth,innerHeight获取 1284 | if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] : 1285 | //是document,用scrollWidth,scrollHeight获取 1286 | isDocument(el) ? el.documentElement['scroll' + dimensionProperty] : 1287 | // 是元素 用offset 1288 | (offset = this.offset()) && offset[dimension] 1289 | 1290 | // 写 1291 | else return this.each(function(idx){ 1292 | el = $(this) 1293 | el.css(dimension, funcArg(this, value, idx, el[dimension]())) 1294 | }) 1295 | } 1296 | }) 1297 | 1298 | // 递归遍历一个节点及其子节点。每遍历一个node执行一次fun(node)。 1299 | function traverseNode(node, fun) { 1300 | fun(node) 1301 | for (var i = 0, len = node.childNodes.length; i < len; i++) 1302 | traverseNode(node.childNodes[i], fun) 1303 | } 1304 | 1305 | // Generate the `after`, `prepend`, `before`, `append`, 1306 | // `insertAfter`, `insertBefore`, `appendTo`, and `prependTo` methods. 1307 | // 用来为原型生成after,prepend等八个与在不同位置插入元素相关的方法 1308 | // adjacencyOperator = ['after', 'prepend', 'before', 'append']; 1309 | adjacencyOperators.forEach(function(operator, operatorIndex) { 1310 | // 区分出这四个操作是“内部操作”还是“外部操作”,所谓“外部操作”指的是对发起这个操作的元素的相邻方向进行的操作,就是after与before,而“内部操作”指的是对发起操作的元素的子元素集合进行的操作,就是append与prepend 1311 | // 选出内部操作 1312 | var inside = operatorIndex % 2 //=> prepend, append 1313 | 1314 | $.fn[operator] = function(){ 1315 | // arguments can be nodes, arrays of nodes, Zepto objects and HTML strings 1316 | var argType, nodes = $.map(arguments, function(arg) { 1317 | var arr = [] 1318 | argType = type(arg) 1319 | // 参数是数组 1320 | if (argType == "array") { 1321 | arg.forEach(function(el) { 1322 | if (el.nodeType !== undefined) return arr.push(el) 1323 | else if ($.zepto.isZ(el)) return arr = arr.concat(el.get()) 1324 | arr = arr.concat(zepto.fragment(el)) 1325 | }) 1326 | return arr 1327 | } 1328 | //传参非 object、array、null,就直接调用zepto.fragment生成DOM 1329 | return argType == "object" || arg == null ? 1330 | arg : zepto.fragment(arg) 1331 | }), 1332 | // 如果$长度>1,需要克隆里面的元素 1333 | parent, copyByClone = this.length > 1 1334 | //为0,不需要操作,直接返回 1335 | if (nodes.length < 1) return this 1336 | 1337 | return this.each(function(_, target){ 1338 | parent = inside ? target : target.parentNode 1339 | 1340 | // convert all methods to a "before" operation 1341 | target = operatorIndex == 0 ? target.nextSibling : // after,target等于下一个兄弟元素,然后将DOM通过insertBefore插入到target前 1342 | operatorIndex == 1 ? target.firstChild : // prepend target为parent的第一个元素,然后将DOM通过insertBefore插入到target前 1343 | operatorIndex == 2 ? target : //before 直接将将DOM通过insertBefore插入到target前 1344 | null // 直接调用$(target).append 1345 | 1346 | //父元素是否在document中 1347 | var parentInDocument = $.contains(document.documentElement, parent) 1348 | 1349 | //遍历待插入的元素 1350 | nodes.forEach(function(node){ 1351 | if (copyByClone) node = node.cloneNode(true) 1352 | //parent元素不存在,没法执行插入操作,直接删除,返回 1353 | else if (!parent) return $(node).remove() 1354 | //插入元素 1355 | parent.insertBefore(node, target) 1356 | 1357 | // 如果插入的事script标签 1358 | // 如果父元素在document里,修正script标签。原因是script标签通过innerHTML加入DOM不执行。需要在全局环境下执行它 1359 | if (parentInDocument) traverseNode(node, function(el){ 1360 | if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' && 1361 | (!el.type || el.type === 'text/javascript') && !el.src){ 1362 | // Node.ownerDocument 只读属性会返回当前节点的顶层的 document 对象。 1363 | var target = el.ownerDocument ? el.ownerDocument.defaultView : window 1364 | target['eval'].call(target, el.innerHTML) 1365 | } 1366 | }) 1367 | }) 1368 | }) 1369 | } 1370 | 1371 | // after => insertAfter 1372 | // prepend => prependTo 1373 | // before => insertBefore 1374 | // append => appendTo 1375 | $.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){ 1376 | $(html)[operator](this) 1377 | return this 1378 | } 1379 | }) 1380 | 1381 | // 将形成的原型对象$.fn为挂载在Z.prototype与zepto.Z.prototype上 1382 | zepto.Z.prototype = Z.prototype = $.fn 1383 | 1384 | // Export internal API functions in the `$.zepto` namespace 1385 | // 将两个方法挂载在zepto对象上 1386 | zepto.uniq = uniq 1387 | zepto.deserializeValue = deserializeValue 1388 | 1389 | // 把zepto挂载在$入口函数上 1390 | $.zepto = zepto 1391 | // 并返回$ 1392 | return $ 1393 | })() 1394 | 1395 | // If `$` is not yet defined, point it to `Zepto` 1396 | // 入口函数挂载在window对象上 1397 | window.Zepto = Zepto 1398 | window.$ === undefined && (window.$ = Zepto) 1399 | -------------------------------------------------------------------------------- /underscore源码学习/underscore注释版.js: -------------------------------------------------------------------------------- 1 | // Underscore.js 1.8.3 2 | // http://underscorejs.org 3 | // (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors 4 | // Underscore may be freely distributed under the MIT license. 5 | // 6 | // 内容引用于: 7 | // hanzichi/underscore-analysis 地址: https://github.com/hanzichi/underscore-analysis/ 8 | // undersercore 源码分析 地址:https://www.gitbook.com/book/yoyoyohamapi/undersercore-analysis/details 9 | // 以及英文原文注释翻译 10 | 11 | 12 | (function() { 13 | 14 | // Baseline setup 15 | // 基本设置、配置 16 | // -------------- 17 | 18 | // Establish the root object, `window` in the browser, or `exports` on the server. 19 | // 将 this 赋值给局部变量 root 20 | // root 的值, 客户端为 `window`, 服务端(node) 中为 `exports` 21 | var root = this; 22 | 23 | // Save the previous value of the `_` variable. 24 | // 将原来全局环境中的变量 `_` 赋值给变量 previousUnderscore 进行缓存 25 | // 在后面的 noConflict 方法中有用到 26 | var previousUnderscore = root._; 27 | 28 | // Save bytes in the minified (but not gzipped) version: 29 | // 缓存变量, 便于压缩代码 30 | // 此处「压缩」指的是压缩到 min.js 版本 31 | // 而不是 gzip 压缩 32 | var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; 33 | 34 | // Create quick reference variables for speed access to core prototypes. 35 | // 缓存变量, 便于压缩代码 36 | // 同时可减少在原型链中的查找次数(提高代码效率) 37 | var 38 | push = ArrayProto.push, 39 | slice = ArrayProto.slice, 40 | toString = ObjProto.toString, 41 | hasOwnProperty = ObjProto.hasOwnProperty; 42 | 43 | // All **ECMAScript 5** native function implementations that we hope to use 44 | // are declared here. 45 | // ES5 原生方法, 如果浏览器支持, 则 underscore 中会优先使用 46 | var 47 | nativeIsArray = Array.isArray, 48 | nativeKeys = Object.keys, 49 | nativeBind = FuncProto.bind, 50 | nativeCreate = Object.create; 51 | 52 | // Naked function reference for surrogate-prototype-swapping. 53 | var Ctor = function(){}; 54 | 55 | // Create a safe reference to the Underscore object for use below. 56 | // 核心函数 57 | // `_` 其实是一个构造函数 58 | // 支持无 new 调用的构造函数(思考 jQuery 的无 new 调用) 59 | // 将传入的参数(实际要操作的数据)赋值给 this._wrapped 属性 60 | // OOP 调用时,_ 相当于一个构造函数 61 | // each 等方法都在该构造函数的原型链上 62 | // _([1, 2, 3]).each(alert) 63 | // _([1, 2, 3]) 相当于无 new 构造了一个新的对象 64 | // 调用了该对象的 each 方法,该方法在该对象构造函数的原型链上 65 | var _ = function(obj) { 66 | // 以下均针对 OOP 形式的调用 67 | // 如果是非 OOP 形式的调用,不会进入该函数内部 68 | 69 | // 如果 obj 已经是 `_` 函数的实例,则直接返回 obj 70 | if (obj instanceof _) 71 | return obj; 72 | 73 | // 如果不是 `_` 函数的实例 74 | // 则调用 new 运算符,返回实例化的对象 75 | if (!(this instanceof _)) 76 | return new _(obj); 77 | 78 | // 将 obj 赋值给 this._wrapped 属性 79 | this._wrapped = obj; 80 | }; 81 | 82 | // Export the Underscore object for **Node.js**, with 83 | // backwards-compatibility for the old `require()` API. If we're in 84 | // the browser, add `_` as a global object. 85 | // 将上面定义的 `_` 局部变量赋值给全局对象中的 `_` 属性 86 | // 即客户端中 window._ = _ 87 | // 服务端(node)中 exports._ = _ 88 | // 同时在服务端向后兼容老的 require() API 89 | // 这样暴露给全局后便可以在全局环境中使用 `_` 变量(方法) 90 | if (typeof exports !== 'undefined') { 91 | if (typeof module !== 'undefined' && module.exports) { 92 | exports = module.exports = _; 93 | } 94 | exports._ = _; 95 | } else { 96 | root._ = _; 97 | } 98 | 99 | // Current version. 100 | // 当前 underscore 版本号 101 | _.VERSION = '1.8.3'; 102 | 103 | // Internal function that returns an efficient (for current engines) version 104 | // of the passed-in callback, to be repeatedly applied in other Underscore 105 | // functions. 106 | // underscore 内部方法 107 | // 根据 this 指向(context 参数) 108 | // 以及 argCount 参数 109 | // 二次操作返回一些回调、迭代方法 110 | var optimizeCb = function(func, context, argCount) { 111 | // 如果没有指定 this 指向,则返回原函数 112 | if (context === void 0) 113 | return func; 114 | switch (argCount == null ? 3 : argCount) { 115 | case 1: return function(value) { 116 | return func.call(context, value); 117 | }; 118 | case 2: return function(value, other) { 119 | return func.call(context, value, other); 120 | }; 121 | 122 | // 如果有指定 this,但没有传入 argCount 参数 123 | // 则执行以下 case 124 | // _.each、_.map 125 | case 3: return function(value, index, collection) { 126 | return func.call(context, value, index, collection); 127 | }; 128 | // _.reduce、_.reduceRight 129 | case 4: return function(accumulator, value, index, collection) { 130 | return func.call(context, accumulator, value, index, collection); 131 | }; 132 | } 133 | 134 | // 其实不用上面的 switch-case 语句 135 | // 直接执行下面的 return 函数就行了 136 | // 不这样做的原因是 call 比 apply 快很多 137 | // .apply 在运行前要对作为参数的数组进行一系列检验和深拷贝,.call 则没有这些步骤 138 | // 具体可以参考: 139 | // https://segmentfault.com/q/1010000007894513 140 | // http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.4.3 141 | // http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.4.4 142 | return function() { 143 | return func.apply(context, arguments); 144 | }; 145 | }; 146 | 147 | // A mostly-internal function to generate callbacks that can be applied 148 | // to each element in a collection, returning the desired result — either 149 | // identity, an arbitrary callback, a property matcher, or a property accessor. 150 | var cb = function(value, context, argCount) { 151 | if (value == null) return _.identity; 152 | if (_.isFunction(value)) return optimizeCb(value, context, argCount); 153 | if (_.isObject(value)) return _.matcher(value); 154 | return _.property(value); 155 | }; 156 | 157 | _.iteratee = function(value, context) { 158 | return cb(value, context, Infinity); 159 | }; 160 | 161 | // An internal function for creating assigner functions. 162 | // 有三个方法用到了这个内部函数 163 | // _.extend & _.extendOwn & _.defaults 164 | // _.extend = createAssigner(_.allKeys); 165 | // _.extendOwn = _.assign = createAssigner(_.keys); 166 | // _.defaults = createAssigner(_.allKeys, true); 167 | var createAssigner = function(keysFunc, undefinedOnly) { 168 | // 返回函数 169 | // 经典闭包(undefinedOnly 参数在返回的函数中被引用) 170 | // 返回的函数参数个数 >= 1 171 | // 将第二个开始的对象参数的键值对 "继承" 给第一个参数 172 | return function(obj) { 173 | var length = arguments.length; 174 | // 只传入了一个参数(或者 0 个?) 175 | // 或者传入的第一个参数是 null 176 | if (length < 2 || obj == null) return obj; 177 | 178 | // 枚举第一个参数除外的对象参数 179 | // 即 arguments[1], arguments[2] ... 180 | for (var index = 1; index < length; index++) { 181 | // source 即为对象参数 182 | var source = arguments[index], 183 | // 提取对象参数的 keys 值 184 | // keysFunc 参数表示 _.keys 185 | // 或者 _.allKeys 186 | keys = keysFunc(source), 187 | l = keys.length; 188 | // 遍历该对象的键值对 189 | for (var i = 0; i < l; i++) { 190 | var key = keys[i]; 191 | // _.extend 和 _.extendOwn 方法 192 | // 没有传入 undefinedOnly 参数,即 !undefinedOnly 为 true 193 | // 即肯定会执行 obj[key] = source[key] 194 | // 后面对象的键值对直接覆盖 obj 195 | // ========================================== 196 | // _.defaults 方法,undefinedOnly 参数为 true 197 | // 即 !undefinedOnly 为 false 198 | // 那么当且仅当 obj[key] 为 undefined 时才覆盖 199 | // 即如果有相同的 key 值,取最早出现的 value 值 200 | // *defaults 中有相同 key 的也是一样取首次出现的 201 | if (!undefinedOnly || obj[key] === void 0) 202 | obj[key] = source[key]; 203 | } 204 | } 205 | 206 | // 返回已经继承后面对象参数属性的第一个参数对象 207 | return obj; 208 | }; 209 | }; 210 | 211 | // An internal function for creating a new object that inherits from another. 212 | // use in `_.create` 213 | var baseCreate = function(prototype) { 214 | // 如果 prototype 参数不是对象 215 | if (!_.isObject(prototype)) return {}; 216 | 217 | // 如果浏览器支持 ES5 Object.create 218 | if (nativeCreate) return nativeCreate(prototype); 219 | 220 | Ctor.prototype = prototype; 221 | var result = new Ctor; 222 | Ctor.prototype = null; 223 | return result; 224 | }; 225 | 226 | // 闭包 227 | var property = function(key){ 228 | return function(obj) { 229 | return obj == null ? void 0 : obj[key]; 230 | }; 231 | }; 232 | 233 | // Helper for collection methods to determine whether a collection 234 | // should be iterated as an array or as an object 235 | // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength 236 | // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 237 | 238 | // Math.pow(2, 53) - 1 是 JavaScript 中能精确表示的最大数字 239 | var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; 240 | 241 | // getLength 函数 242 | // 该函数传入一个参数,返回参数的 length 属性值 243 | // 用来获取 array 以及 arrayLike 元素的 length 属性值 244 | var getLength = property('length'); 245 | 246 | // 判断是否是 ArrayLike Object 247 | // 类数组,即拥有 length 属性并且 length 属性值为 Number 类型的元素 248 | // 包括数组、arguments、HTML Collection 以及 NodeList 等等 249 | // 包括类似 {length: 10} 这样的对象 250 | // 包括字符串、函数等 251 | var isArrayLike = function(collection) { 252 | // 返回参数 collection 的 length 属性值 253 | var length = getLength(collection); 254 | return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; 255 | }; 256 | 257 | 258 | // Collection Functions 259 | // 数组或者对象的扩展方法 260 | // 共 25 个扩展方法 261 | // -------------------- 262 | 263 | // The cornerstone, an `each` implementation, aka `forEach`. 264 | // Handles raw objects in addition to array-likes. Treats all 265 | // sparse array-likes as if they were dense. 266 | // 与 ES5 中 Array.prototype.forEach 使用方法类似 267 | // 遍历数组或者对象的每个元素 268 | // 第一个参数为数组(包括类数组)或者对象 269 | // 第二个参数为迭代方法,对数组或者对象每个元素都执行该方法 270 | // 该方法又能传入三个参数,分别为 (item, index, array)((value, key, obj) for object) 271 | // 与 ES5 中 Array.prototype.forEach 方法传参格式一致 272 | // 第三个参数(可省略)确定第二个参数 iteratee 函数中的(可能有的)this 指向 273 | // 即 iteratee 中出现的(如果有)所有 this 都指向 context 274 | // notice: 不要传入一个带有 key 类型为 number 的对象! 275 | // notice: _.each 方法不能用 return 跳出循环(同样,Array.prototype.forEach 也不行) 276 | _.each = _.forEach = function(obj, iteratee, context) { 277 | 278 | // 根据 context 确定不同的迭代函数 279 | iteratee = optimizeCb(iteratee, context); 280 | var i, length; 281 | 282 | // 如果是类数组 283 | // 默认不会传入类似 {length: 10} 这样的数据 284 | if (isArrayLike(obj)) { 285 | // 遍历 286 | for (i = 0, length = obj.length; i < length; i++) { 287 | iteratee(obj[i], i, obj); 288 | } 289 | } else { // 如果 obj 是对象 290 | // 获取对象的所有 key 值 291 | var keys = _.keys(obj); 292 | // 如果是对象,则遍历处理 values 值 293 | for (i = 0, length = keys.length; i < length; i++) { 294 | iteratee(obj[keys[i]], keys[i], obj); // (value, key, obj) 295 | } 296 | } 297 | // 返回 obj 参数 298 | // 供链式调用(Returns the list for chaining) 299 | // 应该仅 OOP 调用有效 300 | return obj; 301 | }; 302 | 303 | // Return the results of applying the iteratee to each element. 304 | // 与 ES5 中 Array.prototype.map 使用方法类似 305 | // 传参形式与 _.each 方法类似 306 | // 遍历数组(每个元素)或者对象的每个元素(value) 307 | // 对每个元素执行 iteratee 迭代方法 308 | // 将结果保存到新的数组中,并返回 309 | _.map = _.collect = function(obj, iteratee, context) { 310 | // 根据 context 确定不同的迭代函数 311 | iteratee = cb(iteratee, context); 312 | 313 | // 如果传参是对象,则获取它的 keys 值数组(短路表达式) 314 | var keys = !isArrayLike(obj) && _.keys(obj), 315 | // 如果 obj 为对象,则 length 为 key.length 316 | // 如果 obj 为数组,则 length 为 obj.length 317 | length = (keys || obj).length, 318 | results = Array(length); // 结果数组 319 | 320 | // 遍历 321 | for (var index = 0; index < length; index++) { 322 | // 如果 obj 为对象,则 currentKey 为对象键值 key 323 | // 如果 obj 为数组,则 currentKey 为 index 值 324 | var currentKey = keys ? keys[index] : index; 325 | results[index] = iteratee(obj[currentKey], currentKey, obj); 326 | } 327 | 328 | // 返回新的结果数组 329 | return results; 330 | }; 331 | 332 | // Create a reducing function iterating left or right. 333 | // dir === 1 -> _.reduce 334 | // dir === -1 -> _.reduceRight 335 | function createReduce(dir) { 336 | // Optimized iterator function as using arguments.length 337 | // in the main function will deoptimize the, see #1991. 338 | // console.log(memo) 339 | function iterator(obj, iteratee, memo, keys, index, length) { 340 | for (; index >= 0 && index < length; index += dir) { 341 | var currentKey = keys ? keys[index] : index; 342 | // 迭代,返回值供下次迭代调用 343 | memo = iteratee(memo, obj[currentKey], currentKey, obj); 344 | } 345 | // 每次迭代返回值,供下次迭代调用 346 | return memo; 347 | } 348 | // _.reduce(_.reduceRight)可传入的 4 个参数 349 | // obj 数组或者对象 350 | // iteratee 迭代方法,对数组或者对象每个元素执行该方法 351 | // memo 初始值,如果没有,则从 obj 第一个元素开始迭代 352 | // 如果没有,则从 obj 第二个元素开始迭代,将第一个元素作为初始值 353 | // context 为迭代函数中的 this 指向 354 | return function(obj, iteratee, memo, context) { 355 | iteratee = optimizeCb(iteratee, context, 4); 356 | var keys = !isArrayLike(obj) && _.keys(obj), 357 | length = (keys || obj).length, 358 | index = dir > 0 ? 0 : length - 1; 359 | // Determine the initial value if none is provided. 360 | // 如果没有指定初始值 361 | // 则把第一个元素指定为初始值 362 | if (arguments.length < 3) { 363 | memo = obj[keys ? keys[index] : index]; 364 | // 根据 dir 确定是向左还是向右遍历 365 | index += dir; 366 | } 367 | 368 | return iterator(obj, iteratee, memo, keys, index, length); 369 | }; 370 | } 371 | 372 | // **Reduce** builds up a single result from a list of values, aka `inject`, 373 | // or `foldl`. 374 | // 与 ES5 中 Array.prototype.reduce 使用方法类似 375 | // _.reduce(list, iteratee, [memo], [context]) 376 | // _.reduce 方法最多可传入 4 个参数 377 | // memo 为初始值,可选 378 | // context 为指定 iteratee 中 this 指向,可选 379 | _.reduce = _.foldl = _.inject = createReduce(1); 380 | 381 | // The right-associative version of reduce, also known as `foldr`. 382 | // 与 ES5 中 Array.prototype.reduceRight 使用方法类似 383 | _.reduceRight = _.foldr = createReduce(-1); 384 | 385 | // Return the first value which passes a truth test. Aliased as `detect`. 386 | // 寻找数组或者对象中第一个满足条件(predicate 函数返回 true)的元素 387 | // 并返回该元素值 388 | // _.find(list, predicate, [context]) 389 | _.find = _.detect = function(obj, predicate, context) { 390 | var key; 391 | // 如果 obj 是数组,key 为满足条件的下标 392 | if (isArrayLike(obj)) { 393 | key = _.findIndex(obj, predicate, context); 394 | } else { 395 | // 如果 obj 是对象,key 为满足条件的元素的 key 值 396 | key = _.findKey(obj, predicate, context); 397 | } 398 | 399 | // 如果该元素存在,则返回该元素 400 | // 如果不存在,则默认返回 undefined(函数没有返回,即返回 undefined) 401 | if (key !== void 0 && key !== -1) return obj[key]; 402 | }; 403 | 404 | // Return all the elements that pass a truth test. 405 | // Aliased as `select`. 406 | // 与 ES5 中 Array.prototype.filter 使用方法类似 407 | // 寻找数组或者对象中所有满足条件的元素 408 | // 如果是数组,则将 `元素值` 存入数组 409 | // 如果是对象,则将 `value 值` 存入数组 410 | // 返回该数组 411 | // _.filter(list, predicate, [context]) 412 | _.filter = _.select = function(obj, predicate, context) { 413 | var results = []; 414 | 415 | // 根据 this 指向,返回 predicate 函数(判断函数) 416 | predicate = cb(predicate, context); 417 | 418 | // 遍历每个元素,如果符合条件则存入数组 419 | _.each(obj, function(value, index, list) { 420 | if (predicate(value, index, list)) results.push(value); 421 | }); 422 | 423 | return results; 424 | }; 425 | 426 | // Return all the elements for which a truth test fails. 427 | // 寻找数组或者对象中所有不满足条件的元素 428 | // 并以数组方式返回 429 | // 所得结果是 _.filter 方法的补集 430 | _.reject = function(obj, predicate, context) { 431 | return _.filter(obj, _.negate(cb(predicate)), context); 432 | }; 433 | 434 | // Determine whether all of the elements match a truth test. 435 | // Aliased as `all`. 436 | // 与 ES5 中的 Array.prototype.every 方法类似 437 | // 判断数组中的每个元素或者对象中每个 value 值是否都满足 predicate 函数中的判断条件 438 | // 如果是,则返回 ture;否则返回 false(有一个不满足就返回 false) 439 | // _.every(list, [predicate], [context]) 440 | _.every = _.all = function(obj, predicate, context) { 441 | // 根据 this 指向,返回相应 predicate 函数 442 | predicate = cb(predicate, context); 443 | 444 | var keys = !isArrayLike(obj) && _.keys(obj), 445 | length = (keys || obj).length; 446 | 447 | for (var index = 0; index < length; index++) { 448 | var currentKey = keys ? keys[index] : index; 449 | // 如果有一个不能满足 predicate 中的条件 450 | // 则返回 false 451 | if (!predicate(obj[currentKey], currentKey, obj)) 452 | return false; 453 | } 454 | 455 | return true; 456 | }; 457 | 458 | // Determine if at least one element in the object matches a truth test. 459 | // Aliased as `any`. 460 | // 与 ES5 中 Array.prototype.some 方法类似 461 | // 判断数组或者对象中是否有一个元素(value 值 for object)满足 predicate 函数中的条件 462 | // 如果是则返回 true;否则返回 false 463 | // _.some(list, [predicate], [context]) 464 | _.some = _.any = function(obj, predicate, context) { 465 | // 根据 context 返回 predicate 函数 466 | predicate = cb(predicate, context); 467 | // 如果传参是对象,则返回该对象的 keys 数组 468 | var keys = !isArrayLike(obj) && _.keys(obj), 469 | length = (keys || obj).length; 470 | for (var index = 0; index < length; index++) { 471 | var currentKey = keys ? keys[index] : index; 472 | // 如果有一个元素满足条件,则返回 true 473 | if (predicate(obj[currentKey], currentKey, obj)) return true; 474 | } 475 | return false; 476 | }; 477 | 478 | // Determine if the array or object contains a given item (using `===`). 479 | // Aliased as `includes` and `include`. 480 | // 判断数组或者对象中(value 值)是否有指定元素 481 | // 如果是 object,则忽略 key 值,只需要查找 value 值即可 482 | // 即该 obj 中是否有指定的 value 值 483 | // 返回布尔值 484 | _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) { 485 | // 如果是对象,返回 values 组成的数组 486 | if (!isArrayLike(obj)) obj = _.values(obj); 487 | 488 | // fromIndex 表示查询起始位置 489 | // 如果没有指定该参数,则默认从头找起 490 | if (typeof fromIndex != 'number' || guard) fromIndex = 0; 491 | 492 | // _.indexOf 是数组的扩展方法(Array Functions) 493 | // 数组中寻找某一元素 494 | return _.indexOf(obj, item, fromIndex) >= 0; 495 | }; 496 | 497 | // Invoke a method (with arguments) on every item in a collection. 498 | // Calls the method named by methodName on each value in the list. 499 | // Any extra arguments passed to invoke will be forwarded on to the method invocation. 500 | // 数组或者对象中的每个元素都调用 method 方法 501 | // 返回调用后的结果(数组或者关联数组) 502 | // method 参数后的参数会被当做参数传入 method 方法中 503 | // _.invoke(list, methodName, *arguments) 504 | _.invoke = function(obj, method) { 505 | // *arguments 参数 506 | // slice = Array.prototype.slice() 507 | var args = slice.call(arguments, 2); 508 | // 判断 method 是不是函数 509 | var isFunc = _.isFunction(method); 510 | // 用 map 方法对数组或者对象每个元素调用方法 511 | // 返回数组 512 | return _.map(obj, function(value) { 513 | // 如果 method 不是函数,则可能是 obj 的 key 值 514 | // 515 | // var example= [6,7,5]; 516 | // example.sort(); 517 | // 而 obj[method] 可能为函数 518 | var func = isFunc ? method : value[method]; 519 | return func == null ? func : func.apply(value, args); 520 | }); 521 | }; 522 | 523 | // Convenience version of a common use case of `map`: fetching a property. 524 | // 一个数组,元素都是对象 525 | // 根据指定的 key 值 526 | // 返回一个数组,元素都是指定 key 值的 value 值 527 | /* 528 | var property = function(key) { 529 | return function(obj) { 530 | return obj == null ? void 0 : obj[key]; 531 | }; 532 | }; 533 | */ 534 | // _.pluck(list, propertyName) 535 | _.pluck = function(obj, key) { 536 | return _.map(obj, _.property(key)); 537 | }; 538 | 539 | // Convenience version of a common use case of `filter`: selecting only objects 540 | // containing specific `key:value` pairs. 541 | // 根据指定的键值对 542 | // 选择对象 543 | _.where = function(obj, attrs) { 544 | return _.filter(obj, _.matcher(attrs)); 545 | }; 546 | 547 | // Convenience version of a common use case of `find`: getting the first object 548 | // containing specific `key:value` pairs. 549 | // 寻找第一个有指定 key-value 键值对的对象 550 | _.findWhere = function(obj, attrs) { 551 | return _.find(obj, _.matcher(attrs)); 552 | }; 553 | 554 | // Return the maximum element (or element-based computation). 555 | // 寻找数组中的最大元素 556 | // 或者对象中的最大 value 值 557 | // 如果有 iteratee 参数,则求每个元素经过该函数迭代后的最值 558 | // _.max(list, [iteratee], [context]) 559 | _.max = function(obj, iteratee, context) { 560 | var result = -Infinity, lastComputed = -Infinity, 561 | value, computed; 562 | 563 | // 单纯地寻找最值 564 | if (iteratee == null && obj != null) { 565 | // 如果是数组,则寻找数组中最大元素 566 | // 如果是对象,则寻找最大 value 值 567 | obj = isArrayLike(obj) ? obj : _.values(obj); 568 | 569 | for (var i = 0, length = obj.length; i < length; i++) { 570 | value = obj[i]; 571 | if (value > result) { 572 | result = value; 573 | } 574 | 575 | // if(obj[i] > result) { 576 | // result = obj[i]; ???? 为什么要多设一个value参数? 577 | // } 578 | } 579 | } else { // 寻找元素经过迭代后的最值 580 | iteratee = cb(iteratee, context); 581 | 582 | // result 保存结果元素 583 | // lastComputed 保存计算过程中出现的最值 584 | // 遍历元素 585 | _.each(obj, function(value, index, list) { 586 | // 经过迭代函数后的值 587 | computed = iteratee(value, index, list); 588 | // && 的优先级高于 || 589 | if (computed > lastComputed || computed === -Infinity && result === -Infinity) { 590 | result = value; 591 | lastComputed = computed; 592 | } 593 | }); 594 | } 595 | 596 | return result; 597 | }; 598 | 599 | // Return the minimum element (or element-based computation). 600 | // 寻找最小的元素 601 | // 类似 _.max 602 | // _.min(list, [iteratee], [context]) 603 | _.min = function(obj, iteratee, context) { 604 | var result = Infinity, lastComputed = Infinity, 605 | value, computed; 606 | if (iteratee == null && obj != null) { 607 | obj = isArrayLike(obj) ? obj : _.values(obj); 608 | for (var i = 0, length = obj.length; i < length; i++) { 609 | value = obj[i]; 610 | if (value < result) { 611 | result = value; 612 | } 613 | } 614 | } else { 615 | iteratee = cb(iteratee, context); 616 | _.each(obj, function(value, index, list) { 617 | computed = iteratee(value, index, list); 618 | if (computed < lastComputed || computed === Infinity && result === Infinity) { 619 | result = value; 620 | lastComputed = computed; 621 | } 622 | }); 623 | } 624 | return result; 625 | }; 626 | 627 | // Shuffle a collection, using the modern version of the 628 | // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). 629 | // 将数组乱序 630 | // 如果是对象,则返回一个数组,数组由对象 value 值构成 631 | // Fisher-Yates shuffle 算法 632 | // 最优的洗牌算法,复杂度 O(n) 633 | // 乱序不要用 sort + Math.random(),复杂度 O(nlogn) 634 | // 而且,并不是真正的乱序 635 | // @see https://github.com/hanzichi/underscore-analysis/issues/15 636 | // 637 | _.shuffle = function(obj) { 638 | // 如果是对象,则对 value 值进行乱序 639 | var set = isArrayLike(obj) ? obj : _.values(obj); 640 | var length = set.length; 641 | 642 | // 乱序后返回的数组副本(参数是对象则返回乱序后的 value 数组) 643 | var shuffled = Array(length); 644 | 645 | // 枚举元素 646 | for (var index = 0, rand; index < length; index++) { 647 | // 将当前所枚举位置的元素和 `index=rand` 位置的元素交换 648 | rand = _.random(0, index); 649 | if (rand !== index) shuffled[index] = shuffled[rand]; 650 | shuffled[rand] = set[index]; 651 | } 652 | 653 | return shuffled; 654 | }; 655 | 656 | // Sample **n** random values from a collection. 657 | // If **n** is not specified, returns a single random element. 658 | // The internal `guard` argument allows it to work with `map`. 659 | // 随机返回数组或者对象中的一个元素 660 | // 如果指定了参数 `n`,则随机返回 n 个元素组成的数组 661 | // 如果参数是对象,则数组由 values 组成 662 | // 663 | _.sample = function(obj, n, guard) { 664 | // 随机返回一个元素 665 | if (n == null || guard) { 666 | if (!isArrayLike(obj)) obj = _.values(obj); 667 | return obj[_.random(obj.length - 1)]; 668 | } 669 | 670 | // 随机返回 n 个 671 | return _.shuffle(obj).slice(0, Math.max(0, n)); 672 | }; 673 | 674 | // Sort the object's values by a criterion produced by an iteratee. 675 | // 排序 676 | // _.sortBy(list, iteratee, [context]) 677 | _.sortBy = function(obj, iteratee, context) { 678 | iteratee = cb(iteratee, context); 679 | 680 | // 根据指定的 key 返回 values 数组 681 | // _.pluck([{}, {}, {}], 'value') 682 | return _.pluck( 683 | // _.map(obj, function(){}).sort() 684 | // _.map 后的结果 [{}, {}..] 685 | // sort 后的结果 [{}, {}..] 686 | // list 是原数组 687 | _.map(obj, function(value, index, list) { 688 | 689 | return { 690 | value: value, 691 | index: index, 692 | // 元素经过迭代函数迭代后的值 693 | criteria: iteratee(value, index, list) 694 | }; 695 | }).sort(function(left, right) { 696 | var a = left.criteria; 697 | var b = right.criteria; 698 | if (a !== b) { 699 | if (a > b || a === void 0) return 1; 700 | if (a < b || b === void 0) return -1; 701 | } 702 | return left.index - right.index; 703 | }), 'value'); 704 | 705 | }; 706 | 707 | // An internal function used for aggregate "group by" operations. 708 | // behavior 是一个函数参数 709 | // _.groupBy, _.indexBy 以及 _.countBy 其实都是对数组元素进行分类 710 | // 分类规则就是 behavior 函数 711 | var group = function(behavior) { 712 | return function(obj, iteratee, context) { 713 | // 返回结果是一个对象 714 | var result = {}; 715 | iteratee = cb(iteratee, context); 716 | // 遍历元素 717 | _.each(obj, function(value, index) { 718 | // 经过迭代,获取结果值,存为 key 719 | var key = iteratee(value, index, obj); 720 | // 按照不同的规则进行分组操作 721 | // 将变量 result 当做参数传入,能在 behavior 中改变该值 722 | behavior(result, value, key); 723 | }); 724 | // 返回结果对象 725 | return result; 726 | }; 727 | }; 728 | 729 | // Groups the object's values by a criterion. Pass either a string attribute 730 | // to group by, or a function that returns the criterion. 731 | // groupBy_ _.groupBy(list, iteratee, [context]) 732 | // 根据特定规则对数组或者对象中的元素进行分组 733 | // result 是返回对象 734 | // value 是数组元素 735 | // key 是迭代后的值 736 | _.groupBy = group(function(result, value, key) { 737 | // 根据 key 值分组 738 | // key 是元素经过迭代函数后的值 739 | // 或者元素自身的属性值 740 | 741 | // result 对象已经有该 key 值了 742 | if (_.has(result, key)) 743 | result[key].push(value); 744 | else result[key] = [value]; 745 | }); 746 | 747 | // Indexes the object's values by a criterion, similar to `groupBy`, but for 748 | // when you know that your index values will be unique. 749 | _.indexBy = group(function(result, value, key) { 750 | // key 值必须是独一无二的 751 | // 不然后面的会覆盖前面的 752 | // 其他和 _.groupBy 类似 753 | result[key] = value; 754 | }); 755 | 756 | // Counts instances of an object that group by a certain criterion. Pass 757 | // either a string attribute to count by, or a function that returns the 758 | // criterion. 759 | _.countBy = group(function(result, value, key) { 760 | // 不同 key 值元素数量 761 | if (_.has(result, key)) 762 | result[key]++; 763 | else result[key] = 1; 764 | }); 765 | 766 | // Safely create a real, live array from anything iterable. 767 | // 伪数组 -> 数组 768 | // 对象 -> 提取 value 值组成数组 769 | // 返回数组 770 | _.toArray = function(obj) { 771 | if (!obj) return []; 772 | 773 | // 如果是数组,则返回副本数组 774 | // 是否用 obj.concat() 更方便? 775 | // 776 | if (_.isArray(obj)){ 777 | return slice.call(obj); 778 | } 779 | 780 | // 如果是类数组,则重新构造新的数组 781 | // 是否也可以直接用 slice 方法? 782 | if (isArrayLike(obj)){ 783 | return _.map(obj, _.identity); 784 | } 785 | 786 | // 如果是对象,则返回 values 集合 787 | return _.values(obj); 788 | }; 789 | 790 | // Return the number of elements in an object. 791 | // 如果是数组(类数组),返回长度(length 属性) 792 | // 如果是对象,返回键值对数量 793 | _.size = function(obj) { 794 | if (obj == null) return 0; 795 | return isArrayLike(obj) ? obj.length : _.keys(obj).length; 796 | }; 797 | 798 | // Split a collection into two arrays: one whose elements all satisfy the given 799 | // predicate, and one whose elements all do not satisfy the predicate. 800 | // 将数组或者对象中符合条件(predicate)的元素 801 | // 和不符合条件的元素(数组为元素,对象为 value 值) 802 | // 分别放入两个数组中 803 | // 返回一个数组,数组元素为以上两个数组([[pass array], [fail array]]) 804 | _.partition = function(obj, predicate, context) { 805 | predicate = cb(predicate, context); 806 | var pass = [], fail = []; 807 | _.each(obj, function(value, key, obj) { 808 | (predicate(value, key, obj) ? pass : fail).push(value); 809 | }); 810 | return [pass, fail]; 811 | }; 812 | 813 | 814 | // Array Functions 815 | // 数组的扩展方法 816 | // 共 20 个扩展方法 817 | // Note: All array functions will also work on the arguments object. 818 | // However, Underscore functions are not designed to work on "sparse" arrays. 819 | // --------------- 820 | 821 | // Get the first element of an array. Passing **n** will return the first N 822 | // values in the array. Aliased as `head` and `take`. The **guard** check 823 | // allows it to work with `_.map`. 824 | // 返回数组第一个元素 825 | // 如果有参数 n,则返回数组前 n 个元素(组成的数组) 826 | _.first = _.head = _.take = function(array, n, guard) { 827 | // 容错,数组为空则返回 undefined 828 | if (array == null) return void 0; 829 | 830 | // 没指定参数 n,则默认返回第一个元素 831 | if (n == null || guard) return array[0]; 832 | 833 | // 如果传入参数 n,则返回前 n 个元素组成的数组 834 | // 返回前 n 个元素,即剔除后 array.length - n 个元素 835 | return _.initial(array, array.length - n); 836 | }; 837 | 838 | // Returns everything but the last entry of the array. Especially useful on 839 | // the arguments object. Passing **n** will return all the values in 840 | // the array, excluding the last N. 841 | // 传入一个数组 842 | // 返回剔除最后一个元素之后的数组副本 843 | // 如果传入参数 n,则剔除最后 n 个元素 844 | _.initial = function(array, n, guard) { 845 | return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); 846 | }; 847 | 848 | // Get the last element of an array. Passing **n** will return the last N 849 | // values in the array. 850 | // 返回数组最后一个元素 851 | // 如果传入参数 n 852 | // 则返回该数组后 n 个元素组成的数组 853 | // 即剔除前 array.length - n 个元素 854 | _.last = function(array, n, guard) { 855 | // 容错 856 | if (array == null) return void 0; 857 | 858 | // 如果没有指定参数 n,则返回最后一个元素 859 | if (n == null || guard) return array[array.length - 1]; 860 | 861 | // 如果传入参数 n,则返回后 n 个元素组成的数组 862 | // 即剔除前 array.length - n 个元素 863 | return _.rest(array, Math.max(0, array.length - n)); 864 | }; 865 | 866 | // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. 867 | // Especially useful on the arguments object. Passing an **n** will return 868 | // the rest N values in the array. 869 | // 传入一个数组 870 | // 返回剔除第一个元素后的数组副本 871 | // 如果传入参数 n,则剔除前 n 个元素 872 | _.rest = _.tail = _.drop = function(array, n, guard) { 873 | return slice.call(array, n == null || guard ? 1 : n); 874 | }; 875 | 876 | // Trim out all falsy values from an array. 877 | // 去掉数组中所有的假值 878 | // 返回数组副本 879 | // JavaScript 中的假值包括 false、null、undefined、''、NaN、0 880 | // 联想 PHP 中的 array_filter() 函数 881 | // _.identity = function(value) { 882 | // return value; 883 | // }; 884 | _.compact = function(array) { 885 | return _.filter(array, _.identity); 886 | }; 887 | 888 | // Internal implementation of a recursive `flatten` function. 889 | // 递归调用数组,将数组展开 890 | // 即 [1, 2, [3, 4]] => [1, 2, 3, 4] 891 | // flatten(array, shallow, false) 892 | // flatten(arguments, true, true, 1) 893 | // flatten(arguments, true, true) 894 | // flatten(arguments, false, false, 1) 895 | // ===== // 896 | // input => Array 或者 arguments 897 | // shallow => 是否只展开一层 898 | // strict === true,通常和 shallow === true 配合使用 899 | // 表示只展开一层,但是不保存非数组元素(即无法展开的基础类型) 900 | // flatten([[1, 2], 3, 4], true, true) => [1, 2] 901 | // flatten([[1, 2], 3, 4], false, true) = > [] 902 | // startIndex => 从 input 的第几项开始展开 903 | // ===== // 904 | // 可以看到,如果 strict 参数为 true,那么 shallow 也为 true 905 | // 也就是展开一层,同时把非数组过滤 906 | // [[1, 2], [3, 4], 5, 6] => [1, 2, 3, 4] 907 | var flatten = function(input, shallow, strict, startIndex) { 908 | // output 数组保存结果 909 | // 即 flatten 方法返回数据 910 | // idx 为 output 的累计数组下标 911 | var output = [], idx = 0; 912 | 913 | // 根据 startIndex 变量确定需要展开的起始位置 914 | for (var i = startIndex || 0, length = getLength(input); i < length; i++) { 915 | var value = input[i]; 916 | // 数组 或者 arguments 917 | // 注意 isArrayLike 还包括 {length: 10} 这样的,过滤掉 918 | if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { 919 | // flatten current level of array or arguments object 920 | // (!shallow === true) => (shallow === false) 921 | // 则表示需深度展开 922 | // 继续递归展开 923 | if (!shallow){ 924 | // flatten 方法返回数组 925 | // 将上面定义的 value 重新赋值 926 | value = flatten(value, shallow, strict); 927 | } 928 | // 递归展开到最后一层(没有嵌套的数组了) 929 | // 或者 (shallow === true) => 只展开一层 930 | // value 值肯定是一个数组 931 | var j = 0, len = value.length; 932 | 933 | // 这一步貌似没有必要 934 | // 毕竟 JavaScript 的数组会自动扩充 935 | // 但是这样写,感觉比较好,对于元素的 push 过程有个比较清晰的认识 936 | output.length += len; 937 | 938 | // 将 value 数组的元素添加到 output 数组中 939 | while (j < len) { 940 | output[idx++] = value[j++]; 941 | } 942 | } else if (!strict) { 943 | // (!strict === true) => (strict === false) 944 | // 如果是深度展开,即 shallow 参数为 false 945 | // 那么当最后 value 不是数组,是基本类型时 946 | // 肯定会走到这个 else-if 判断中 947 | // 而如果此时 strict 为 true,则不能跳到这个分支内部 948 | // 所以 shallow === false 如果和 strict === true 搭配 949 | // 调用 flatten 方法得到的结果永远是空数组 [] 950 | output[idx++] = value; 951 | } 952 | } 953 | 954 | return output; 955 | }; 956 | 957 | // Flatten out an array, either recursively (by default), or just one level. 958 | // 将嵌套的数组展开 959 | // 如果参数 (shallow === true),则仅展开一层 960 | // _.flatten([1, [2], [3, [[4]]]]); 961 | // => [1, 2, 3, 4]; 962 | // ====== // 963 | // _.flatten([1, [2], [3, [[4]]]], true); 964 | // => [1, 2, 3, [[4]]]; 965 | _.flatten = function(array, shallow) { 966 | // array => 需要展开的数组 967 | // shallow => 是否只展开一层 968 | // false 为 flatten 方法 strict 变量 969 | return flatten(array, shallow, false); 970 | }; 971 | 972 | // Return a version of the array that does not contain the specified value(s). 973 | // without_.without(array, *values) 974 | // Returns a copy of the array with all instances of the values removed. 975 | // ====== // 976 | // _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); 977 | // => [2, 3, 4] 978 | // ===== // 979 | // 从数组中移除指定的元素 980 | // 返回移除后的数组副本 981 | _.without = function(array) { 982 | // slice.call(arguments, 1) 983 | // 将 arguments 转为数组(同时去掉第一个元素,即数组) 984 | // 之后便可以调用 _.difference 方法 985 | // slice.call(arguments,1)获得的是要去掉的元素 986 | return _.difference(array, slice.call(arguments, 1)); 987 | }; 988 | 989 | // Produce a duplicate-free version of the array. If the array has already 990 | // been sorted, you have the option of using a faster algorithm. 991 | // Aliased as `unique`. 992 | // 数组去重 993 | // 如果第二个参数 `isSorted` 为 true 994 | // 则说明事先已经知道数组有序 995 | // 程序会跑一个更快的算法(一次线性比较,元素和数组前一个元素比较即可) 996 | // 如果有第三个参数 iteratee,则对数组每个元素迭代 997 | // 对迭代之后的结果进行去重 998 | // 返回去重后的数组(array 的子数组) 999 | // PS: 暴露的 API 中没 context 参数 1000 | // _.uniq(array, [isSorted], [iteratee]) 1001 | _.uniq = _.unique = function(array, isSorted, iteratee, context) { 1002 | // 没有传入 isSorted 参数 1003 | // 转为 _.unique(array, false, undefined, iteratee) 1004 | if (!_.isBoolean(isSorted)) { 1005 | context = iteratee; 1006 | iteratee = isSorted; 1007 | isSorted = false; 1008 | } 1009 | 1010 | // 如果有迭代函数 1011 | // 则根据 this 指向二次返回新的迭代函数 1012 | if (iteratee != null) 1013 | iteratee = cb(iteratee, context); 1014 | 1015 | // 结果数组,是 array 的子集 1016 | var result = []; 1017 | 1018 | // 已经出现过的元素(或者经过迭代过的值) 1019 | // 用来过滤重复值 1020 | var seen = []; 1021 | 1022 | for (var i = 0, length = getLength(array); i < length; i++) { 1023 | var value = array[i], 1024 | // 如果指定了迭代函数 1025 | // 则对数组每一个元素进行迭代 1026 | // 迭代函数传入的三个参数通常是 value, index, array 形式 1027 | computed = iteratee ? iteratee(value, i, array) : value; 1028 | 1029 | // 如果是有序数组,则当前元素只需跟上一个元素对比即可 1030 | // 用 seen 变量保存上一个元素 1031 | if (isSorted) { 1032 | // 如果 i === 0,是第一个元素,则直接 push 1033 | // 否则比较当前元素是否和前一个元素相等 1034 | if (!i || seen !== computed) result.push(value); 1035 | // seen 保存当前元素,供下一次对比 1036 | seen = computed; 1037 | } else if (iteratee) { 1038 | // 如果 seen[] 中没有 computed 这个元素值 1039 | if (!_.contains(seen, computed)) { 1040 | seen.push(computed); 1041 | result.push(value); 1042 | } 1043 | } else if (!_.contains(result, value)) { 1044 | // 如果不用经过迭代函数计算,也就不用 seen[] 变量了 1045 | result.push(value); 1046 | } 1047 | } 1048 | 1049 | return result; 1050 | }; 1051 | 1052 | // Produce an array that contains the union: each distinct element from all of 1053 | // the passed-in arrays. 1054 | // union_.union(*arrays) 1055 | // Computes the union of the passed-in arrays: 1056 | // the list of unique items, in order, that are present in one or more of the arrays. 1057 | // ========== // 1058 | // _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); 1059 | // => [1, 2, 3, 101, 10] 1060 | // ========== // 1061 | // 将多个数组的元素集中到一个数组中 1062 | // 并且去重,返回数组副本 1063 | _.union = function() { 1064 | // 首先用 flatten 方法将传入的数组展开成一个数组 1065 | // 然后就可以愉快地调用 _.uniq 方法了 1066 | // 假设 _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); 1067 | // arguments 为 [[1, 2, 3], [101, 2, 1, 10], [2, 1]] 1068 | // shallow 参数为 true,展开一层 1069 | // 结果为 [1, 2, 3, 101, 2, 1, 10, 2, 1] 1070 | // 然后对其去重 1071 | return _.uniq(flatten(arguments, true, true)); 1072 | }; 1073 | 1074 | // Produce an array that contains every item shared between all the 1075 | // passed-in arrays. 1076 | // 寻找几个数组中共有的元素 1077 | // 将这些每个数组中都有的元素存入另一个数组中返回 1078 | // _.intersection(*arrays) 1079 | // _.intersection([1, 2, 3, 1], [101, 2, 1, 10, 1], [2, 1, 1]) 1080 | // => [1, 2] 1081 | // 注意:返回的结果数组是去重的 1082 | _.intersection = function(array) { 1083 | // 结果数组 1084 | var result = []; 1085 | 1086 | // 传入的参数(数组)个数 1087 | var argsLength = arguments.length; 1088 | 1089 | // 遍历第一个数组的元素 1090 | for (var i = 0, length = getLength(array); i < length; i++) { 1091 | var item = array[i]; 1092 | 1093 | // 如果 result[] 中已经有 item 元素了,continue 1094 | // 即 array 中出现了相同的元素 1095 | // 返回的 result[] 其实是个 "集合"(是去重的) 1096 | if (_.contains(result, item)) continue; 1097 | 1098 | // 判断其他参数数组中是否都有 item 这个元素 1099 | for (var j = 1; j < argsLength; j++) { 1100 | if (!_.contains(arguments[j], item)) 1101 | break; 1102 | } 1103 | 1104 | // 遍历其他参数数组完毕 1105 | // j === argsLength 说明其他参数数组中都有 item 元素 1106 | // 则将其放入 result[] 中 1107 | if (j === argsLength) 1108 | result.push(item); 1109 | } 1110 | 1111 | return result; 1112 | }; 1113 | 1114 | // Take the difference between one array and a number of other arrays. 1115 | // Only the elements present in just the first array will remain. 1116 | // _.difference(array, *others) 1117 | // Similar to without, but returns the values from array that are not present in the other arrays. 1118 | // ===== // 1119 | // _.difference([1, 2, 3, 4, 5], [5, 2, 10]); 1120 | // => [1, 3, 4] 1121 | // ===== // 1122 | // 剔除 array 数组中在 others 数组中出现的元素 1123 | _.difference = function(array) { 1124 | // 将 others 数组展开一层 1125 | // rest[] 保存展开后的元素组成的数组 1126 | // strict 参数为 true 1127 | // 不可以这样用 _.difference([1, 2, 3, 4, 5], [5, 2], 10); 1128 | // 10 就会取不到 1129 | var rest = flatten(arguments, true, true, 1); 1130 | // 遍历 array,过滤 1131 | return _.filter(array, function(value){ 1132 | 1133 | // 如果 value 存在在 rest 中,则过滤掉 1134 | return !_.contains(rest, value); 1135 | }); 1136 | }; 1137 | 1138 | // Zip together multiple lists into a single array -- elements that share 1139 | // an index go together. 1140 | // ===== // 1141 | // _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); 1142 | // => [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]] 1143 | // ===== // 1144 | // 将多个数组中相同位置的元素归类 1145 | // 返回一个数组 1146 | _.zip = function() { 1147 | return _.unzip(arguments); 1148 | }; 1149 | 1150 | // Complement of _.zip. Unzip accepts an array of arrays and groups 1151 | // each array's elements on shared indices 1152 | // The opposite of zip. Given an array of arrays, 1153 | // returns a series of new arrays, 1154 | // the first of which contains all of the first elements in the input arrays, 1155 | // the second of which contains all of the second elements, and so on. 1156 | // ===== // 1157 | // _.unzip([["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]); 1158 | // => [['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]] 1159 | // ===== // 1160 | _.unzip = function(array) { 1161 | var length = array && _.max(array, getLength).length || 0; 1162 | var result = Array(length); 1163 | 1164 | for (var index = 0; index < length; index++) { 1165 | result[index] = _.pluck(array, index); 1166 | } 1167 | return result; 1168 | }; 1169 | 1170 | // Converts lists into objects. Pass either a single array of `[key, value]` 1171 | // pairs, or two parallel arrays of the same length -- one of keys, and one of 1172 | // the corresponding values. 1173 | // 将数组转化为对象 1174 | _.object = function(list, values) { 1175 | var result = {}; 1176 | for (var i = 0, length = getLength(list); i < length; i++) { 1177 | if (values) { 1178 | result[list[i]] = values[i]; 1179 | } else { 1180 | result[list[i][0]] = list[i][1]; 1181 | } 1182 | } 1183 | return result; 1184 | }; 1185 | 1186 | // Generator function to create the findIndex and findLastIndex functions 1187 | // (dir === 1) => 从前往后找 1188 | // (dir === -1) => 从后往前找 1189 | function createPredicateIndexFinder(dir) { 1190 | // 经典闭包 1191 | return function(array, predicate, context) { 1192 | predicate = cb(predicate, context); 1193 | var length = getLength(array); 1194 | 1195 | // 根据 dir 变量来确定数组遍历的起始位置 1196 | var index = dir > 0 ? 0 : length - 1; 1197 | 1198 | for (; index >= 0 && index < length; index += dir) { 1199 | // 找到第一个符合条件的元素 1200 | // 并返回下标值 1201 | if (predicate(array[index], index, array)) 1202 | 1203 | return index; 1204 | } 1205 | 1206 | return -1; 1207 | }; 1208 | } 1209 | 1210 | 1211 | // Returns the first index on an array-like that passes a predicate test 1212 | // 从前往后找到数组中 `第一个满足条件` 的元素,并返回下标值 1213 | // 没找到返回 -1 1214 | // _.findIndex(array, predicate, [context]) 1215 | _.findIndex = createPredicateIndexFinder(1); 1216 | 1217 | // 从后往前找到数组中 `第一个满足条件` 的元素,并返回下标值 1218 | // 没找到返回 -1 1219 | // _.findLastIndex(array, predicate, [context]) 1220 | _.findLastIndex = createPredicateIndexFinder(-1); 1221 | 1222 | // Use a comparator function to figure out the smallest index at which 1223 | // an object should be inserted so as to maintain order. Uses binary search. 1224 | // The iteratee may also be the string name of the property to sort by (eg. length). 1225 | // ===== // 1226 | // _.sortedIndex([10, 20, 30, 40, 50], 35); 1227 | // => 3 1228 | // ===== // 1229 | // var stooges = [{name: 'moe', age: 40}, {name: 'curly', age: 60}]; 1230 | // _.sortedIndex(stooges, {name: 'larry', age: 50}, 'age'); 1231 | // => 1 1232 | // ===== // 1233 | // 二分查找 1234 | // 将一个元素插入已排序的数组 1235 | // 返回该插入的位置下标 1236 | // _.sortedIndex(list, value, [iteratee], [context]) 1237 | _.sortedIndex = function(array, obj, iteratee, context) { 1238 | // 注意 cb 方法 1239 | // iteratee 为空 || 为 String 类型(key 值)时会返回不同方法 1240 | iteratee = cb(iteratee, context, 1); 1241 | // 经过迭代函数计算的值 1242 | // 可打印 iteratee 出来看看 1243 | var value = iteratee(obj); 1244 | var low = 0, high = getLength(array); 1245 | 1246 | // 二分查找 1247 | while (low < high) { 1248 | var mid = Math.floor((low + high) / 2); 1249 | if (iteratee(array[mid]) < value) 1250 | low = mid + 1; 1251 | else 1252 | high = mid; 1253 | } 1254 | 1255 | return low; 1256 | }; 1257 | 1258 | // Generator function to create the indexOf and lastIndexOf functions 1259 | // _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex); 1260 | // _.lastIndexOf = createIndexFinder(-1, _.findLastIndex); 1261 | function createIndexFinder(dir, predicateFind, sortedIndex) { 1262 | // API 调用形式 1263 | // _.indexOf(array, value, [isSorted]) 1264 | // _.indexOf(array, value, [fromIndex]) 1265 | // _.lastIndexOf(array, value, [fromIndex]) 1266 | return function(array, item, idx) { 1267 | var i = 0, length = getLength(array); 1268 | 1269 | // 如果 idx 为 Number 类型 1270 | // 则规定查找位置的起始点 1271 | // 那么第三个参数不是 [isSorted] 1272 | // 所以不能用二分查找优化了 1273 | // 只能遍历查找 1274 | if (typeof idx == 'number') { 1275 | if (dir > 0) { // 正向查找 1276 | // 重置查找的起始位置 1277 | i = idx >= 0 ? idx : Math.max(idx + length, i); 1278 | } else { // 反向查找 1279 | // 如果是反向查找,重置 length 属性值 1280 | length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; 1281 | } 1282 | } else if (sortedIndex && idx && length) { 1283 | // 能用二分查找加速的条件 1284 | // 有序 & idx !== 0 && length !== 0 1285 | 1286 | // 用 _.sortIndex 找到有序数组中 item 正好插入的位置 1287 | idx = sortedIndex(array, item); 1288 | 1289 | // 如果正好插入的位置的值和 item 刚好相等 1290 | // 说明该位置就是 item 第一次出现的位置 1291 | // 返回下标 1292 | // 否则即是没找到,返回 -1 1293 | return array[idx] === item ? idx : -1; 1294 | } 1295 | 1296 | // 特判,如果要查找的元素是 NaN 类型 1297 | // 如果 item !== item 1298 | // 那么 item => NaN 1299 | if (item !== item) { 1300 | idx = predicateFind(slice.call(array, i, length), _.isNaN); 1301 | return idx >= 0 ? idx + i : -1; 1302 | } 1303 | 1304 | // O(n) 遍历数组 1305 | // 寻找和 item 相同的元素 1306 | // 特判排除了 item 为 NaN 的情况 1307 | // 可以放心地用 `===` 来判断是否相等了 1308 | for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { 1309 | if (array[idx] === item) return idx; 1310 | } 1311 | 1312 | return -1; 1313 | }; 1314 | } 1315 | 1316 | // Return the position of the first occurrence of an item in an array, 1317 | // or -1 if the item is not included in the array. 1318 | // If the array is large and already in sort order, pass `true` 1319 | // for **isSorted** to use binary search. 1320 | // _.indexOf(array, value, [isSorted]) 1321 | // 找到数组 array 中 value 第一次出现的位置 1322 | // 并返回其下标值 1323 | // 如果数组有序,则第三个参数可以传入 true 1324 | // 这样算法效率会更高(二分查找) 1325 | // [isSorted] 参数表示数组是否有序 1326 | // 同时第三个参数也可以表示 [fromIndex] (见下面的 _.lastIndexOf) 1327 | _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex); 1328 | 1329 | // 和 _indexOf 相似 1330 | // 反序查找 1331 | // _.lastIndexOf(array, value, [fromIndex]) 1332 | // [fromIndex] 参数表示从倒数第几个开始往前找 1333 | _.lastIndexOf = createIndexFinder(-1, _.findLastIndex); 1334 | 1335 | // Generate an integer Array containing an arithmetic progression. A port of 1336 | // the native Python `range()` function. See 1337 | // [the Python documentation](http://docs.python.org/library/functions.html#range). 1338 | // 返回某一个范围内的数组成的数组 1339 | _.range = function(start, stop, step) { 1340 | if (stop == null) { 1341 | stop = start || 0; 1342 | start = 0; 1343 | } 1344 | 1345 | step = step || 1; 1346 | 1347 | // 返回数组的长度 1348 | var length = Math.max(Math.ceil((stop - start) / step), 0); 1349 | 1350 | // 返回的数组 1351 | var range = Array(length); 1352 | 1353 | for (var idx = 0; idx < length; idx++, start += step) { 1354 | range[idx] = start; 1355 | } 1356 | 1357 | return range; 1358 | }; 1359 | 1360 | 1361 | // Function (ahem) Functions 1362 | // 函数的扩展方法 1363 | // 共 14 个扩展方法 1364 | // ------------------ 1365 | 1366 | // Determines whether to execute a function as a constructor 1367 | // or a normal function with the provided arguments 1368 | var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) { 1369 | // 非 new 调用 _.bind 返回的方法(即 bound) 1370 | // callingContext 不是 boundFunc 的一个实例 1371 | if (!(callingContext instanceof boundFunc)) 1372 | return sourceFunc.apply(context, args); 1373 | 1374 | // 如果是用 new 调用 _.bind 返回的方法 1375 | 1376 | // self 为 sourceFunc 的实例,继承了它的原型链 1377 | // self 理论上是一个空对象(还没赋值),但是有原型链 1378 | var self = baseCreate(sourceFunc.prototype); 1379 | 1380 | // 用 new 生成一个构造函数的实例 1381 | // 正常情况下是没有返回值的,即 result 值为 undefined 1382 | // 如果构造函数有返回值 1383 | // 如果返回值是对象(非 null),则 new 的结果返回这个对象 1384 | // 否则返回实例 1385 | // @see http://www.cnblogs.com/zichi/p/4392944.html 1386 | var result = sourceFunc.apply(self, args); 1387 | 1388 | // 如果构造函数返回了对象 1389 | // 则 new 的结果是这个对象 1390 | // 返回这个对象 1391 | if (_.isObject(result)) return result; 1392 | 1393 | // 否则返回 self 1394 | // var result = sourceFunc.apply(self, args); 1395 | // self 对象当做参数传入 1396 | // 会直接改变值 1397 | return self; 1398 | }; 1399 | 1400 | // Create a function bound to a given object (assigning `this`, and arguments, 1401 | // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if 1402 | // available. 1403 | // ES5 bind 方法的扩展(polyfill) 1404 | // 将 func 中的 this 指向 context(对象) 1405 | // _.bind(function, object, *arguments) 1406 | // 可选的 arguments 参数会被当作 func 的参数传入 1407 | // func 在调用时,会优先用 arguments 参数,然后使用 _.bind 返回方法所传入的参数 1408 | _.bind = function(func, context) { 1409 | // 如果浏览器支持 ES5 bind 方法,并且 func 上的 bind 方法没有被重写 1410 | // 则优先使用原生的 bind 方法 1411 | // if (nativeBind && func.bind === nativeBind) 1412 | // return nativeBind.apply(func, slice.call(arguments, 1)); 1413 | // 如果传入的参数 func 不是方法,则抛出错误 1414 | if (!_.isFunction(func)) 1415 | throw new TypeError('Bind must be called on a function'); 1416 | 1417 | // polyfill 1418 | // 经典闭包,函数返回函数 1419 | // args 获取优先使用的参数 1420 | var args = slice.call(arguments, 2); 1421 | var bound = function() { 1422 | // args.concat(slice.call(arguments)) 1423 | // 最终函数的实际调用参数由两部分组成 1424 | // 一部分是传入 _.bind 的参数(会被优先调用) 1425 | // 另一部分是传入 bound(_.bind 所返回方法)的参数 1426 | return executeBound(func, bound, context, this, args.concat(slice.call(arguments))); 1427 | }; 1428 | 1429 | return bound; 1430 | }; 1431 | 1432 | // Partially apply a function by creating a version that has had some of its 1433 | // arguments pre-filled, without changing its dynamic `this` context. _ acts 1434 | // as a placeholder, allowing any combination of arguments to be pre-filled. 1435 | // _.partial(function, *arguments) 1436 | // _.partial 能返回一个方法 1437 | // pre-fill 该方法的一些参数 1438 | _.partial = function(func) { 1439 | // 提取希望 pre-fill 的参数 1440 | // 如果传入的是 _,则这个位置的参数暂时空着,等待手动填入 1441 | var boundArgs = slice.call(arguments, 1); 1442 | var bound = function() { 1443 | var position = 0, length = boundArgs.length; 1444 | var args = Array(length); 1445 | for (var i = 0; i < length; i++) { 1446 | // 如果该位置的参数为 _,则用 bound 方法的参数填充这个位置 1447 | // args 为调用 _.partial 方法的 pre-fill 的参数 & bound 方法的 arguments 1448 | args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i]; 1449 | } 1450 | // bound 方法还有剩余的 arguments,添上去 1451 | while (position < arguments.length) 1452 | args.push(arguments[position++]); 1453 | 1454 | return executeBound(func, bound, this, this, args); 1455 | }; 1456 | 1457 | return bound; 1458 | }; 1459 | 1460 | // Bind a number of an object's methods to that object. Remaining arguments 1461 | // are the method names to be bound. Useful for ensuring that all callbacks 1462 | // defined on an object belong to it. 1463 | // 指定一系列方法(methodNames)中的 this 指向(object) 1464 | // _.bindAll(object, *methodNames) 1465 | _.bindAll = function(obj) { 1466 | var i, length = arguments.length, key; 1467 | // 如果只传入了一个参数(obj),没有传入 methodNames,则报错 1468 | if (length <= 1) 1469 | throw new Error('bindAll must be passed function names'); 1470 | 1471 | // 遍历 methodNames 1472 | for (i = 1; i < length; i++) { 1473 | key = arguments[i]; 1474 | // 逐个绑定 1475 | obj[key] = _.bind(obj[key], obj); 1476 | } 1477 | return obj; 1478 | }; 1479 | 1480 | // Memoize an expensive function by storing its results. 1481 | //「记忆化」,存储中间运算结果,提高效率 1482 | // 参数 hasher 是个 function,用来计算 key 1483 | // 如果传入了 hasher,则用 hasher 来计算 key 1484 | // 否则用 key 参数直接当 key(即 memoize 方法传入的第一个参数) 1485 | // _.memoize(function, [hashFunction]) 1486 | // 适用于需要大量重复求值的场景 1487 | // 比如递归求解菲波那切数 1488 | // @http://www.jameskrob.com/memoize.html 1489 | // create hash for storing "expensive" function outputs 1490 | // run expensive function 1491 | // check whether function has already been run with given arguments via hash lookup 1492 | // if false - run function, and store output in hash 1493 | // if true, return output stored in hash 1494 | // 1495 | // ?????? 1496 | _.memoize = function(func, hasher) { 1497 | var memoize = function(key) { 1498 | // 储存变量,方便使用 1499 | var cache = memoize.cache; 1500 | 1501 | // 求 process._kill();ey 1502 | // 如果传入了 hasher,则用 hasher 函数来计算 key 1503 | // 否则用 参数 key(即 memoize 方法传入的第一个参数)当 key 1504 | var address = '' + (hasher ? hasher.apply(this, arguments) : key); 1505 | // 如果这个 key 还没被 hash 过(还没求过值) 1506 | if (!_.has(cache, address)) 1507 | cache[address] = func.apply(this, arguments); 1508 | 1509 | // 返回 1510 | return cache[address]; 1511 | }; 1512 | 1513 | // cache 对象被当做 key-value 键值对缓存中间运算结果 1514 | memoize.cache = {}; 1515 | // console.log(memoize.cache); 1516 | // 返回一个函数(经典闭包) 1517 | return memoize; 1518 | }; 1519 | 1520 | // Delays a function for the given number of milliseconds, and then calls 1521 | // it with the arguments supplied. 1522 | // 延迟触发某方法 1523 | // _.delay(function, wait, *arguments) 1524 | // 如果传入了 arguments 参数,则会被当作 func 的参数在触发时调用 1525 | // 其实是封装了「延迟触发某方法」,使其复用 1526 | _.delay = function(func, wait) { 1527 | // 获取 *arguments 1528 | // 是 func 函数所需要的参数 1529 | var args = slice.call(arguments, 2); 1530 | return setTimeout(function(){ 1531 | // 将参数赋予 func 函数 1532 | return func.apply(null, args); 1533 | }, wait); 1534 | }; 1535 | 1536 | // Defers a function, scheduling it to run after the current call stack has 1537 | // cleared. 1538 | // 和 setTimeout(func, 0) 相似(源码看来似乎应该是 setTimeout(func, 1)) 1539 | // _.defer(function, *arguments) 1540 | // 如果传入 *arguments,会被当做参数,和 _.delay 调用方式类似(少了第二个参数) 1541 | // 其实核心还是调用了 _.delay 方法,但第二个参数(wait 参数)设置了默认值为 1 1542 | // 如何使得方法能设置默认值?用 _.partial 方法 1543 | _.defer = _.partial(_.delay, _, 1); 1544 | 1545 | // Returns a function, that, when invoked, will only be triggered at most once 1546 | // during a given window of time. Normally, the throttled function will run 1547 | // as much as it can, without ever going more than once per `wait` duration; 1548 | // but if you'd like to disable the execution on the leading edge, pass 1549 | // `{leading: false}`. To disable execution on the trailing edge, ditto. 1550 | // 函数节流(如果有连续事件响应,则每间隔一定时间段触发) 1551 | // 每间隔 wait(Number) milliseconds 触发一次 func 方法 1552 | // 如果 options 参数传入 {leading: false} 1553 | // 那么不会马上触发(等待 wait milliseconds 后第一次触发 func) 1554 | // 如果 options 参数传入 {trailing: false} 1555 | // 那么最后一次回调不会被触发 1556 | // **Notice: options 不能同时设置 leading 和 trailing 为 false** 1557 | // 示例: 1558 | // var throttled = _.throttle(updatePosition, 100); 1559 | // $(window).scroll(throttled); 1560 | // 调用方式(注意看 A 和 B console.log 打印的位置): 1561 | // _.throttle(function, wait, [options]) 1562 | // sample 1: _.throttle(function(){}, 1000) 1563 | // print: A, B, B, B ... 1564 | // sample 2: _.throttle(function(){}, 1000, {leading: false}) 1565 | // print: B, B, B, B ... 1566 | // sample 3: _.throttle(function(){}, 1000, {trailing: false}) 1567 | // print: A, A, A, A ... 1568 | // ----------------------------------------- // 1569 | _.throttle = function(func, wait, options) { 1570 | var context, args, result; 1571 | // setTimeout 的 handler 1572 | var timeout = null; 1573 | // 标记时间戳 1574 | // 上一次执行回调的时间戳 1575 | var previous = 0; 1576 | // 如果没有传入 options 参数 1577 | // 则将 options 参数置为空对象 1578 | if (!options) 1579 | options = {}; 1580 | 1581 | var later = function() { 1582 | // 如果 options.leading === false 1583 | // 则每次触发回调后将 previous 置为 0 1584 | // 否则置为当前时间戳 1585 | previous = options.leading === false ? 0 : _.now(); 1586 | timeout = null; 1587 | result = func.apply(context, args); 1588 | 1589 | // 这里的 timeout 变量一定是 null 了吧 1590 | //检测是为了 防止递归调用,产生新的timeout 1591 | if (!timeout) 1592 | context = args = null; 1593 | }; 1594 | 1595 | // 以滚轮事件为例(scroll) 1596 | // 每次触发滚轮事件即执行这个返回的方法 1597 | // _.throttle 方法返回的函数 1598 | return function() { 1599 | 1600 | // 记录当前时间戳 1601 | var now = _.now(); 1602 | // console.log(now); 1603 | // console.log("====="); 1604 | // console.log(previous); 1605 | // console.log("+++"); 1606 | // 第一次执行回调(此时 previous 为 0,之后 previous 值为上一次时间戳) 1607 | // 并且如果程序设定第一个回调不是立即执行的(options.leading === false) 1608 | // 则将 previous 值(表示上次执行的时间戳)设为 now 的时间戳(第一次触发时) 1609 | // 表示刚执行过,这次就不用执行了 1610 | if (!previous && options.leading === false) 1611 | previous = now; 1612 | // 距离下次触发 func 还需要等待的时间 1613 | var remaining = wait - (now - previous); 1614 | context = this; 1615 | args = arguments; 1616 | // 要么是到了间隔时间了,随即触发方法(remaining <= 0) 1617 | // 要么是没有传入 {leading: false},且第一次触发回调,即立即触发 1618 | // 此时 previous 为 0,wait - (now - previous) 也满足 <= 0 1619 | // 之后便会把 previous 值迅速置为 now 1620 | // ========= // 1621 | // remaining > wait,表示客户端系统时间被调整过 1622 | // 则马上执行 func 函数 1623 | // @see https://blog.coding.net/blog/the-difference-between-throttle-and-debounce-in-underscorejs 1624 | if (remaining <= 0 || remaining > wait) { 1625 | if (timeout) { 1626 | clearTimeout(timeout); 1627 | // 解除引用,防止内存泄露 1628 | timeout = null; 1629 | } 1630 | // 重置前一次触发的时间戳 1631 | previous = now; 1632 | // 触发方法 1633 | // result 为该方法返回值 1634 | result = func.apply(context, args); 1635 | // 引用置为空,防止内存泄露 1636 | // 感觉这里的 timeout 肯定是 null 啊?这个 if 判断没必要吧? 1637 | if (!timeout) 1638 | context = args = null; 1639 | } else if (!timeout && options.trailing !== false) { // 最后一次需要触发的情况 1640 | // 如果已经存在一个定时器,则不会进入该 if 分支 1641 | // 如果 {trailing: false},即最后一次不需要触发了,也不会进入这个分支 1642 | // 间隔 remaining milliseconds 后触发 later 方法 1643 | timeout = setTimeout(later, remaining); 1644 | } 1645 | // 回调返回值 1646 | return result; 1647 | }; 1648 | }; 1649 | 1650 | // Returns a function, that, as long as it continues to be invoked, will not 1651 | // be triggered. The function will be called after it stops being called for 1652 | // N milliseconds. If `immediate` is passed, trigger the function on the 1653 | // leading edge, instead of the trailing. 1654 | // 函数去抖(连续事件触发结束后只触发一次) 1655 | // sample 1: _.debounce(function(){}, 1000) 1656 | // 连续事件结束后的 1000ms 后触发 1657 | // sample 1: _.debounce(function(){}, 1000, true) 1658 | // 连续事件触发后立即触发(此时会忽略第二个参数) 1659 | _.debounce = function(func, wait, immediate) { 1660 | var timeout, args, context, timestamp, result; 1661 | 1662 | var later = function() { 1663 | // 定时器设置的回调 later 方法的触发时间,和连续事件触发的最后一次时间戳的间隔 1664 | // 如果间隔为 wait(或者刚好大于 wait),则触发事件 1665 | var last = _.now() - timestamp; 1666 | 1667 | // 时间间隔 last 在 [0, wait) 中 1668 | // 还没到触发的点,则继续设置定时器 1669 | // last 值应该不会小于 0 吧? 1670 | if (last < wait && last >= 0) { 1671 | timeout = setTimeout(later, wait - last); 1672 | } else { 1673 | // 到了可以触发的时间点 1674 | timeout = null; 1675 | // 可以触发了 1676 | // 并且不是设置为立即触发的 1677 | // 因为如果是立即触发(callNow),也会进入这个回调中 1678 | // 主要是为了将 timeout 值置为空,使之不影响下次连续事件的触发 1679 | // 如果不是立即执行,随即执行 func 方法 1680 | if (!immediate) { 1681 | // 执行 func 函数 1682 | result = func.apply(context, args); 1683 | // 这里的 timeout 一定是 null 了吧 1684 | // 感觉这个判断多余了 1685 | if (!timeout) 1686 | context = args = null; 1687 | } 1688 | } 1689 | }; 1690 | 1691 | // 嗯,闭包返回的函数,是可以传入参数的 1692 | // 也是 DOM 事件所触发的回调函数 1693 | return function() { 1694 | // 可以指定 this 指向 1695 | context = this; 1696 | args = arguments; 1697 | 1698 | // 每次触发函数,更新时间戳 1699 | // later 方法中取 last 值时用到该变量 1700 | // 判断距离上次触发事件是否已经过了 wait seconds 了 1701 | // 即我们需要距离最后一次事件触发 wait seconds 后触发这个回调方法 1702 | timestamp = _.now(); 1703 | 1704 | // 立即触发需要满足两个条件 1705 | // immediate 参数为 true,并且 timeout 还没设置 1706 | // immediate 参数为 true 是显而易见的 1707 | // 如果去掉 !timeout 的条件,就会一直触发,而不是触发一次 1708 | // 因为第一次触发后已经设置了 timeout,所以根据 timeout 是否为空可以判断是否是首次触发 1709 | var callNow = immediate && !timeout; 1710 | 1711 | // 设置 wait seconds 后触发 later 方法 1712 | // 无论是否 callNow(如果是 callNow,也进入 later 方法,去 later 方法中判断是否执行相应回调函数) 1713 | // 在某一段的连续触发中,只会在第一次触发时进入这个 if 分支中 1714 | if (!timeout) 1715 | // 设置了 timeout,所以以后不会进入这个 if 分支了 1716 | timeout = setTimeout(later, wait); 1717 | 1718 | // 如果是立即触发 1719 | if (callNow) { 1720 | // func 可能是有返回值的 1721 | result = func.apply(context, args); 1722 | // 解除引用 1723 | context = args = null; 1724 | } 1725 | 1726 | return result; 1727 | }; 1728 | }; 1729 | 1730 | // Returns the first function passed as an argument to the second, 1731 | // allowing you to adjust arguments, run code before and after, and 1732 | // conditionally execute the original function. 1733 | _.wrap = function(func, wrapper) { 1734 | return _.partial(wrapper, func); 1735 | }; 1736 | 1737 | // Returns a negated version of the passed-in predicate. 1738 | // 返回一个 predicate 方法的对立方法 1739 | // 即该方法可以对原来的 predicate 迭代结果值取补集 1740 | _.negate = function(predicate) { 1741 | return function() { 1742 | return !predicate.apply(this, arguments); 1743 | }; 1744 | }; 1745 | 1746 | // Returns a function that is the composition of a list of functions, each 1747 | // consuming the return value of the function that follows. 1748 | // _.compose(*functions) 1749 | // var tmp = _.compose(f, g, h) 1750 | // tmp(args) => f(g(h(args))) 1751 | _.compose = function() { 1752 | var args = arguments; // funcs 1753 | var start = args.length - 1; // 倒序调用 1754 | return function() { 1755 | var i = start; 1756 | 1757 | var result = args[start].apply(this, arguments); 1758 | // 一个一个方法地执行 1759 | while (i--) 1760 | result = args[i].call(this, result); 1761 | return result; 1762 | }; 1763 | }; 1764 | 1765 | // Returns a function that will only be executed on and after the Nth call. 1766 | // 第 times 触发执行 func(事实上之后的每次触发还是会执行 func) 1767 | // 有什么用呢? 1768 | // 如果有 N 个异步事件,所有异步执行完后执行该回调,即 func 方法(联想 eventproxy) 1769 | // _.after 会返回一个函数 1770 | // 当这个函数第 times 被执行的时候 1771 | // 触发 func 方法 1772 | _.after = function(times, func) { 1773 | return function() { 1774 | // 函数被触发了 times 了,则执行 func 函数 1775 | // 事实上 times 次后如果函数继续被执行,也会触发 func 1776 | if (--times < 1) { 1777 | return func.apply(this, arguments); 1778 | } 1779 | }; 1780 | }; 1781 | 1782 | // Returns a function that will only be executed up to (but not including) the Nth call. 1783 | // 函数至多被调用 times - 1 次((but not including) the Nth call) 1784 | // func 函数会触发 time - 1 次(Creates a version of the function that can be called no more than count times) 1785 | // func 函数有个返回值,前 time - 1 次触发的返回值都是将参数代入重新计算的 1786 | // 第 times 开始的返回值为第 times - 1 次时的返回值(不重新计算) 1787 | // The result of the last function call is memoized and returned when count has been reached. 1788 | _.before = function(times, func) { 1789 | var memo; 1790 | return function() { 1791 | if (--times > 0) { 1792 | // 缓存函数执行结果 1793 | memo = func.apply(this, arguments); 1794 | } 1795 | 1796 | // func 引用置为空,其实不置为空也用不到 func 了 1797 | if (times <= 1) 1798 | func = null; 1799 | 1800 | // 前 times - 1 次触发,memo 都是分别计算返回 1801 | // 第 times 次开始,memo 值同 times - 1 次时的 memo 1802 | return memo; 1803 | }; 1804 | }; 1805 | 1806 | // Returns a function that will be executed at most one time, no matter how 1807 | // often you call it. Useful for lazy initialization. 1808 | // 函数至多只能被调用一次 1809 | // 适用于这样的场景,某些函数只能被初始化一次,不得不设置一个变量 flag 1810 | // 初始化后设置 flag 为 true,之后不断 check flag 1811 | // ====== // 1812 | // 其实是调用了 _.before 方法,并且将 times 参数设置为了默认值 2(也就是 func 至多能被调用 2 - 1 = 1 次) 1813 | _.once = _.partial(_.before, 2); 1814 | 1815 | 1816 | // Object Functions 1817 | // 对象的扩展方法 1818 | // 共 38 个扩展方法 1819 | // ---------------- 1820 | 1821 | // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. 1822 | // IE < 9 下 不能用 for key in ... 来枚举对象的某些 key 1823 | // 比如重写了对象的 `toString` 方法,这个 key 值就不能在 IE < 9 下用 for in 枚举到 1824 | // IE < 9,{toString: null}.propertyIsEnumerable('toString') 返回 false 1825 | // IE < 9,重写的 `toString` 属性被认为不可枚举 1826 | // 据此可以判断是否在 IE < 9 浏览器环境中 1827 | var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); 1828 | 1829 | // IE < 9 下不能用 for in 来枚举的 key 值集合 1830 | // 其实还有个 `constructor` 属性 1831 | // 个人觉得可能是 `constructor` 和其他属性不属于一类 1832 | // nonEnumerableProps[] 中都是方法 1833 | // 而 constructor 表示的是对象的构造函数 1834 | // 所以区分开来了 1835 | var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', 1836 | 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; 1837 | 1838 | // obj 为需要遍历键值对的对象 1839 | // keys 为键数组 1840 | // 利用 JavaScript 按值传递的特点 1841 | // 传入数组作为参数,能直接改变数组的值 1842 | function collectNonEnumProps(obj, keys) { 1843 | var nonEnumIdx = nonEnumerableProps.length; 1844 | var constructor = obj.constructor; 1845 | 1846 | // 获取对象的原型 1847 | // 如果 obj 的 constructor 被重写 1848 | // 则 proto 变量为 Object.prototype 1849 | // 如果没有被重写 1850 | // 则为 obj.constructor.prototype 1851 | var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto; 1852 | 1853 | // Constructor is a special case. 1854 | // `constructor` 属性需要特殊处理 (是否有必要?) 1855 | // see https://github.com/hanzichi/underscore-analysis/issues/3 1856 | // 如果 obj 有 `constructor` 这个 key 1857 | // 并且该 key 没有在 keys 数组中 1858 | // 存入 keys 数组 1859 | var prop = 'constructor'; 1860 | if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); 1861 | 1862 | // 遍历 nonEnumerableProps 数组中的 keys 1863 | while (nonEnumIdx--) { 1864 | prop = nonEnumerableProps[nonEnumIdx]; 1865 | // prop in obj 应该肯定返回 true 吧?是否有判断必要? 1866 | // obj[prop] !== proto[prop] 判断该 key 是否来自于原型链 1867 | // 即是否重写了原型链上的属性 1868 | if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) { 1869 | keys.push(prop); 1870 | } 1871 | } 1872 | } 1873 | 1874 | // Retrieve the names of an object's own properties. 1875 | // Delegates to **ECMAScript 5**'s native `Object.keys` 1876 | // ===== // 1877 | // _.keys({one: 1, two: 2, three: 3}); 1878 | // => ["one", "two", "three"] 1879 | // ===== // 1880 | // 返回一个对象的 keys 组成的数组 1881 | // 仅返回 own enumerable properties 组成的数组 1882 | _.keys = function(obj) { 1883 | // 容错 1884 | // 如果传入的参数不是对象,则返回空数组 1885 | if (!_.isObject(obj)) return []; 1886 | 1887 | // 如果浏览器支持 ES5 Object.key() 方法 1888 | // 则优先使用该方法 1889 | if (nativeKeys) return nativeKeys(obj); 1890 | 1891 | var keys = []; 1892 | 1893 | // own enumerable properties 1894 | for (var key in obj) 1895 | // hasOwnProperty 1896 | if (_.has(obj, key)) keys.push(key); 1897 | 1898 | // Ahem, IE < 9. 1899 | // IE < 9 下不能用 for in 来枚举某些 key 值 1900 | // 传入 keys 数组为参数 1901 | // 因为 JavaScript 下函数参数按值传递 1902 | // 所以 keys 当做参数传入后会在 `collectNonEnumProps` 方法中改变值 1903 | if (hasEnumBug) collectNonEnumProps(obj, keys); 1904 | 1905 | return keys; 1906 | }; 1907 | 1908 | // Retrieve all the property names of an object. 1909 | // 返回一个对象的 keys 数组 1910 | // 不仅仅是 own enumerable properties 1911 | // 还包括原型链上继承的属性 1912 | _.allKeys = function(obj) { 1913 | // 容错 1914 | // 不是对象,则返回空数组 1915 | if (!_.isObject(obj)) return []; 1916 | 1917 | var keys = []; 1918 | for (var key in obj) keys.push(key); 1919 | 1920 | // Ahem, IE < 9. 1921 | // IE < 9 下的 bug,同 _.keys 方法 1922 | if (hasEnumBug) collectNonEnumProps(obj, keys); 1923 | 1924 | return keys; 1925 | }; 1926 | 1927 | // Retrieve the values of an object's properties. 1928 | // ===== // 1929 | // _.values({one: 1, two: 2, three: 3}); 1930 | // => [1, 2, 3] 1931 | // ===== // 1932 | // 将一个对象的所有 values 值放入数组中 1933 | // 仅限 own properties 上的 values 1934 | // 不包括原型链上的 1935 | // 并返回该数组 1936 | _.values = function(obj) { 1937 | // 仅包括 own properties 1938 | var keys = _.keys(obj); 1939 | var length = keys.length; 1940 | var values = Array(length); 1941 | for (var i = 0; i < length; i++) { 1942 | values[i] = obj[keys[i]]; 1943 | } 1944 | return values; 1945 | }; 1946 | 1947 | // Returns the results of applying the iteratee to each element of the object 1948 | // In contrast to _.map it returns an object 1949 | // 跟 _.map 方法很像 1950 | // 但是是专门为对象服务的 map 方法 1951 | // 迭代函数改变对象的 values 值 1952 | // 返回对象副本 1953 | _.mapObject = function(obj, iteratee, context) { 1954 | // 迭代函数 1955 | // 对每个键值对进行迭代 1956 | iteratee = cb(iteratee, context); 1957 | 1958 | var keys = _.keys(obj), 1959 | length = keys.length, 1960 | results = {}, // 对象副本,该方法返回的对象 1961 | currentKey; 1962 | 1963 | for (var index = 0; index < length; index++) { 1964 | currentKey = keys[index]; 1965 | // key 值不变 1966 | // 对每个 value 值用迭代函数迭代 1967 | // 返回经过函数运算后的值 1968 | results[currentKey] = iteratee(obj[currentKey], currentKey, obj); 1969 | } 1970 | return results; 1971 | }; 1972 | 1973 | // Convert an object into a list of `[key, value]` pairs. 1974 | // 将一个对象转换为元素为 [key, value] 形式的数组 1975 | // _.pairs({one: 1, two: 2, three: 3}); 1976 | // => [["one", 1], ["two", 2], ["three", 3]] 1977 | _.pairs = function(obj) { 1978 | var keys = _.keys(obj); 1979 | var length = keys.length; 1980 | var pairs = Array(length); 1981 | for (var i = 0; i < length; i++) { 1982 | pairs[i] = [keys[i], obj[keys[i]]]; 1983 | } 1984 | return pairs; 1985 | }; 1986 | 1987 | // Invert the keys and values of an object. The values must be serializable. 1988 | // 将一个对象的 key-value 键值对颠倒 1989 | // 即原来的 key 为 value 值,原来的 value 值为 key 值 1990 | // 需要注意的是,value 值不能重复(不然后面的会覆盖前面的) 1991 | // 且新构造的对象符合对象构造规则 1992 | // 并且返回新构造的对象 1993 | _.invert = function(obj) { 1994 | // 返回的新的对象 1995 | var result = {}; 1996 | var keys = _.keys(obj); 1997 | for (var i = 0, length = keys.length; i < length; i++) { 1998 | result[obj[keys[i]]] = keys[i]; 1999 | } 2000 | return result; 2001 | }; 2002 | 2003 | // Return a sorted list of the function names available on the object. 2004 | // Aliased as `methods` 2005 | // 传入一个对象 2006 | // 遍历该对象的键值对(包括 own properties 以及 原型链上的) 2007 | // 如果某个 value 的类型是方法(function),则将该 key 存入数组 2008 | // 将该数组排序后返回 2009 | _.functions = _.methods = function(obj) { 2010 | // 返回的数组 2011 | var names = []; 2012 | 2013 | // if IE < 9 2014 | // 且对象重写了 `nonEnumerableProps` 数组中的某些方法 2015 | // 那么这些方法名是不会被返回的 2016 | // 可见放弃了 IE < 9 可能对 `toString` 等方法的重写支持 2017 | for (var key in obj) { 2018 | // 如果某个 key 对应的 value 值类型是函数 2019 | // 则将这个 key 值存入数组 2020 | if (_.isFunction(obj[key])) names.push(key); 2021 | } 2022 | 2023 | // 返回排序后的数组 2024 | return names.sort(); 2025 | }; 2026 | 2027 | // Extend a given object with all the properties in passed-in object(s). 2028 | // extend_.extend(destination, *sources) 2029 | // Copy all of the properties in the source objects over to the destination object 2030 | // and return the destination object 2031 | // It's in-order, so the last source will override properties of the same name in previous arguments. 2032 | // 将几个对象上(第二个参数开始,根据参数而定)的所有键值对添加到 destination 对象(第一个参数)上 2033 | // 因为 key 值可能会相同,所以后面的(键值对)可能会覆盖前面的 2034 | // 参数个数 >= 1 2035 | _.extend = createAssigner(_.allKeys); 2036 | 2037 | // Assigns a given object with all the own properties in the passed-in object(s) 2038 | // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) 2039 | // 跟 extend 方法类似,但是只把 own properties 拷贝给第一个参数对象 2040 | // 只继承 own properties 的键值对 2041 | // 参数个数 >= 1 2042 | _.extendOwn = _.assign = createAssigner(_.keys); 2043 | 2044 | // Returns the first key on an object that passes a predicate test 2045 | // 跟数组方法的 _.findIndex 类似 2046 | // 找到对象的键值对中第一个满足条件的键值对 2047 | // 并返回该键值对 key 值 2048 | _.findKey = function(obj, predicate, context) { 2049 | predicate = cb(predicate, context); 2050 | var keys = _.keys(obj), key; 2051 | // 遍历键值对 2052 | for (var i = 0, length = keys.length; i < length; i++) { 2053 | key = keys[i]; 2054 | // 符合条件,直接返回 key 值 2055 | if (predicate(obj[key], key, obj)) return key; 2056 | } 2057 | }; 2058 | 2059 | // Return a copy of the object only containing the whitelisted properties. 2060 | // 根据一定的需求(key 值,或者通过 predicate 函数返回真假) 2061 | // 返回拥有一定键值对的对象副本 2062 | // 第二个参数可以是一个 predicate 函数 2063 | // 也可以是 >= 0 个 key 2064 | // _.pick(object, *keys) 2065 | // Return a copy of the object 2066 | // filtered to only have values for the whitelisted keys (or array of valid keys) 2067 | // Alternatively accepts a predicate indicating which keys to pick. 2068 | /* 2069 | _.pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age'); 2070 | => {name: 'moe', age: 50} 2071 | _.pick({name: 'moe', age: 50, userid: 'moe1'}, ['name', 'age']); 2072 | => {name: 'moe', age: 50} 2073 | _.pick({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) { 2074 | return _.isNumber(value); 2075 | }); 2076 | => {age: 50} 2077 | */ 2078 | _.pick = function(object, oiteratee, context) { 2079 | // result 为返回的对象副本 2080 | var result = {}, obj = object, iteratee, keys; 2081 | 2082 | // 容错 2083 | if (obj == null) return result; 2084 | 2085 | // 如果第二个参数是函数 2086 | if (_.isFunction(oiteratee)) { 2087 | keys = _.allKeys(obj); 2088 | iteratee = optimizeCb(oiteratee, context); 2089 | } else { 2090 | // 如果第二个参数不是函数 2091 | // 则后面的 keys 可能是数组 2092 | // 也可能是连续的几个并列的参数 2093 | // 用 flatten 将它们展开 2094 | keys = flatten(arguments, false, false, 1); 2095 | 2096 | // 也转为 predicate 函数判断形式 2097 | // 将指定 key 转化为 predicate 函数 2098 | iteratee = function(value, key, obj) { return key in obj; }; 2099 | obj = Object(obj); 2100 | } 2101 | 2102 | for (var i = 0, length = keys.length; i < length; i++) { 2103 | var key = keys[i]; 2104 | var value = obj[key]; 2105 | // 满足条件 2106 | if (iteratee(value, key, obj)) result[key] = value; 2107 | } 2108 | return result; 2109 | }; 2110 | 2111 | // Return a copy of the object without the blacklisted properties. 2112 | // 跟 _.pick 方法相对 2113 | // 返回 _.pick 的补集 2114 | // 即返回没有指定 keys 值的对象副本 2115 | // 或者返回不能通过 predicate 函数的对象副本 2116 | _.omit = function(obj, iteratee, context) { 2117 | if (_.isFunction(iteratee)) { 2118 | // _.negate 方法对 iteratee 的结果取反 2119 | iteratee = _.negate(iteratee); 2120 | } else { 2121 | var keys = _.map(flatten(arguments, false, false, 1), String); 2122 | iteratee = function(value, key) { 2123 | return !_.contains(keys, key); 2124 | }; 2125 | } 2126 | return _.pick(obj, iteratee, context); 2127 | }; 2128 | 2129 | // _.defaults(object, *defaults) 2130 | // Fill in a given object with default properties. 2131 | // Fill in undefined properties in object 2132 | // with the first value present in the following list of defaults objects. 2133 | // 和 _.extend 非常类似 2134 | // 区别是如果 *defaults 中出现了和 object 中一样的键 2135 | // 则不覆盖 object 的键值对 2136 | // 如果 *defaults 多个参数对象中有相同 key 的对象 2137 | // 则取最早出现的 value 值 2138 | // 参数个数 >= 1 2139 | _.defaults = createAssigner(_.allKeys, true); 2140 | 2141 | // Creates an object that inherits from the given prototype object. 2142 | // If additional properties are provided then they will be added to the 2143 | // created object. 2144 | // 给定 prototype 2145 | // 以及一些 own properties 2146 | // 构造一个新的对象并返回 2147 | // _.crypto.createECDH(curve) = function(prototype, props) { 2148 | // var result = baseCreate(prototype); 2149 | 2150 | // // 将 props 的键值对覆盖 result 对象 2151 | // if (props) _.extendOwn(result, props); 2152 | // return result; 2153 | // }; 2154 | 2155 | // Create a (shallow-cloned) duplicate of an object. 2156 | // 对象的 `浅复制` 副本 2157 | // 注意点:所有嵌套的对象或者数组都会跟原对象用同一个引用 2158 | // 所以是为浅复制,而不是深度克隆 2159 | _.clone = function(obj) { 2160 | // 容错,如果不是对象或者数组类型,则可以直接返回 2161 | // 因为一些基础类型是直接按值传递的 2162 | // 思考,arguments 呢? Nodelists 呢? HTML Collections 呢? 2163 | if (!_.isObject(obj)) 2164 | return obj; 2165 | 2166 | // 如果是数组,则用 obj.slice() 返回数组副本 2167 | // 如果是对象,则提取所有 obj 的键值对覆盖空对象,返回 2168 | return _.isArray(obj) ? obj.slice() : _.extend({}, obj); 2169 | }; 2170 | 2171 | // Invokes interceptor with the obj, and then returns obj. 2172 | // The primary purpose of this method is to "tap into" a method chain, in 2173 | // order to perform operations on intermediate results within the chain. 2174 | // _.chain([1,2,3,200]) 2175 | // .filter(function(num) { return num % 2 == 0; }) 2176 | // .tap(alert) 2177 | // .map(function(num) { return num * num }) 2178 | // .value(); 2179 | // => // [2, 200] (alerted) 2180 | // => [4, 40000] 2181 | // 主要是用在链式调用中 2182 | // 对中间值立即进行处理 2183 | _.tap = function(obj, interceptor) { 2184 | interceptor(obj); 2185 | return obj; 2186 | }; 2187 | 2188 | // Returns whether an object has a given set of `key:value` pairs. 2189 | // attrs 参数为一个对象 2190 | // 判断 object 对象中是否有 attrs 中的所有 key-value 键值对 2191 | // 返回布尔值 2192 | _.isMatch = function(object, attrs) { 2193 | // 提取 attrs 对象的所有 keys 2194 | var keys = _.keys(attrs), length = keys.length; 2195 | 2196 | // 如果 object 为空 2197 | // 根据 attrs 的键值对数量返回布尔值 2198 | if (object == null) return !length; 2199 | 2200 | // 这一步有必要? 2201 | var obj = Object(object); 2202 | 2203 | // 遍历 attrs 对象键值对 2204 | for (var i = 0; i < length; i++) { 2205 | var key = keys[i]; 2206 | 2207 | // 如果 obj 对象没有 attrs 对象的某个 key 2208 | // 或者对于某个 key,它们的 value 值不同 2209 | // 则证明 object 并不拥有 attrs 的所有键值对 2210 | // 则返回 false 2211 | if (attrs[key] !== obj[key] || !(key in obj)) return false; 2212 | } 2213 | 2214 | return true; 2215 | }; 2216 | 2217 | 2218 | // Internal recursive comparison function for `isEqual`. 2219 | // "内部的"/ "递归地"/ "比较" 2220 | // 该内部方法会被递归调用 2221 | var eq = function(a, b, aStack, bStack) { 2222 | // Identical objects are equal. `0 === -0`, but they aren't identical. 2223 | // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). 2224 | // a === b 时 2225 | // 需要注意 `0 === -0` 这个 special case 2226 | // 0 和 -0 被认为不相同(unequal) 2227 | // 至于原因可以参考上面的链接 2228 | if (a === b) return a !== 0 || 1 / a === 1 / b; 2229 | 2230 | // A strict comparison is necessary because `null == undefined`. 2231 | // 如果 a 和 b 有一个为 null(或者 undefined) 2232 | // 判断 a === b 2233 | if (a == null || b == null) return a === b; 2234 | 2235 | // Unwrap any wrapped objects. 2236 | // 如果 a 和 b 是 underscore OOP 的对象 2237 | // 那么比较 _wrapped 属性值(Unwrap) 2238 | if (a instanceof _) a = a._wrapped; 2239 | if (b instanceof _) b = b._wrapped; 2240 | 2241 | // Compare `[[Class]]` names. 2242 | // 用 Object.prototype.toString.call 方法获取 a 变量类型 2243 | var className = toString.call(a); 2244 | 2245 | // 如果 a 和 b 类型不相同,则返回 false 2246 | // 类型都不同了还比较个蛋! 2247 | if (className !== toString.call(b)) return false; 2248 | 2249 | switch (className) { 2250 | // Strings, numbers, regular expressions, dates, and booleans are compared by value. 2251 | // 以上五种类型的元素可以直接根据其 value 值来比较是否相等 2252 | case '[object RegExp]': 2253 | // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') 2254 | case '[object String]': 2255 | // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is 2256 | // equivalent to `new String("5")`. 2257 | // 转为 String 类型进行比较 2258 | return '' + a === '' + b; 2259 | 2260 | // RegExp 和 String 可以看做一类 2261 | // 如果 obj 为 RegExp 或者 String 类型 2262 | // 那么 '' + obj 会将 obj 强制转为 String 2263 | // 根据 '' + a === '' + b 即可判断 a 和 b 是否相等 2264 | // ================ 2265 | 2266 | case '[object Number]': 2267 | // `NaN`s are equivalent, but non-reflexive. 2268 | // Object(NaN) is equivalent to NaN 2269 | // 如果 +a !== +a 2270 | // 那么 a 就是 NaN 2271 | // 判断 b 是否也是 NaN 即可 2272 | if (+a !== +a) return +b !== +b; 2273 | 2274 | // An `egal` comparison is performed for other numeric values. 2275 | // 排除了 NaN 干扰 2276 | // 还要考虑 0 的干扰 2277 | // 用 +a 将 Number() 形式转为基本类型 2278 | // 即 +Number(1) ==> 1 2279 | // 0 需要特判 2280 | // 如果 a 为 0,判断 1 / +a === 1 / b 2281 | // 否则判断 +a === +b 2282 | return +a === 0 ? 1 / +a === 1 / b : +a === +b; 2283 | 2284 | // 如果 a 为 Number 类型 2285 | // 要注意 NaN 这个 special number 2286 | // NaN 和 NaN 被认为 equal 2287 | // ================ 2288 | 2289 | case '[object Date]': 2290 | case '[object Boolean]': 2291 | // Coerce dates and booleans to numeric primitive values. Dates are compared by their 2292 | // millisecond representations. Note that invalid dates with millisecond representations 2293 | // of `NaN` are not equivalent. 2294 | return +a === +b; 2295 | 2296 | // Date 和 Boolean 可以看做一类 2297 | // 如果 obj 为 Date 或者 Boolean 2298 | // 那么 +obj 会将 obj 转为 Number 类型 2299 | // 然后比较即可 2300 | // +new Date() 是当前时间距离 1970 年 1 月 1 日 0 点的毫秒数 2301 | // +true => 1 2302 | // +new Boolean(false) => 0 2303 | } 2304 | 2305 | 2306 | // 判断 a 是否是数组 2307 | var areArrays = className === '[object Array]'; 2308 | 2309 | // 如果 a 不是数组类型 2310 | if (!areArrays) { 2311 | // 如果 a 不是 object 或者 b 不是 object 2312 | // 则返回 false 2313 | if (typeof a != 'object' || typeof b != 'object') return false; 2314 | 2315 | // 通过上个步骤的 if 过滤 2316 | // !!保证到此的 a 和 b 均为对象!! 2317 | 2318 | // Objects with different constructors are not equivalent, but `Object`s or `Array`s 2319 | // from different frames are. 2320 | // 通过构造函数来判断 a 和 b 是否相同 2321 | // 但是,如果 a 和 b 的构造函数不同 2322 | // 也并不一定 a 和 b 就是 unequal 2323 | // 比如 a 和 b 在不同的 iframes 中! 2324 | // aCtor instanceof aCtor 这步有点不大理解,啥用? 2325 | var aCtor = a.constructor, bCtor = b.constructor; 2326 | if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor && 2327 | _.isFunction(bCtor) && bCtor instanceof bCtor) 2328 | && ('constructor' in a && 'constructor' in b)) { 2329 | return false; 2330 | } 2331 | } 2332 | 2333 | // Assume equality for cyclic structures. The algorithm for detecting cyclic 2334 | // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. 2335 | 2336 | // Initializing stack of traversed objects. 2337 | // It's done here since we only need them for objects and arrays comparison. 2338 | // 第一次调用 eq() 函数,没有传入 aStack 和 bStack 参数 2339 | // 之后递归调用都会传入这两个参数 2340 | aStack = aStack || []; 2341 | bStack = bStack || []; 2342 | 2343 | var length = aStack.length; 2344 | 2345 | while (length--) { 2346 | // Linear search. Performance is inversely proportional to the number of 2347 | // unique nested structures. 2348 | if (aStack[length] === a) return bStack[length] === b; 2349 | } 2350 | 2351 | // Add the first object to the stack of traversed objects. 2352 | aStack.push(a); 2353 | bStack.push(b); 2354 | 2355 | // Recursively compare objects and arrays. 2356 | // 将嵌套的对象和数组展开 2357 | // 如果 a 是数组 2358 | // 因为嵌套,所以需要展开深度比较 2359 | if (areArrays) { 2360 | // Compare array lengths to determine if a deep comparison is necessary. 2361 | // 根据 length 判断是否应该继续递归对比 2362 | length = a.length; 2363 | 2364 | // 如果 a 和 b length 属性大小不同 2365 | // 那么显然 a 和 b 不同 2366 | // return false 不用继续比较了 2367 | if (length !== b.length) return false; 2368 | 2369 | // Deep compare the contents, ignoring non-numeric properties. 2370 | while (length--) { 2371 | // 递归 2372 | if (!eq(a[length], b[length], aStack, bStack)) return false; 2373 | } 2374 | } else { 2375 | // 如果 a 不是数组 2376 | // 进入这个判断分支 2377 | 2378 | // Deep compare objects. 2379 | // 两个对象的深度比较 2380 | var keys = _.keys(a), key; 2381 | length = keys.length; 2382 | 2383 | // Ensure that both objects contain the same number of properties before comparing deep equality. 2384 | // a 和 b 对象的键数量不同 2385 | // 那还比较毛? 2386 | if (_.keys(b).length !== length) return false; 2387 | 2388 | while (length--) { 2389 | // Deep compare each member 2390 | // 递归比较 2391 | key = keys[length]; 2392 | if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; 2393 | } 2394 | } 2395 | 2396 | // Remove the first object from the stack of traversed objects. 2397 | // 与 aStack.push(a) 对应 2398 | // 此时 aStack 栈顶元素正是 a 2399 | // 而代码走到此步 2400 | // a 和 b isEqual 确认 2401 | // 所以 a,b 两个元素可以出栈 2402 | aStack.pop(); 2403 | bStack.pop(); 2404 | 2405 | // 深度搜索递归比较完毕 2406 | // 放心地 return true 2407 | return true; 2408 | }; 2409 | 2410 | // Perform a deep comparison to check if two objects are equal. 2411 | // 判断两个对象是否一样 2412 | // new Boolean(true),true 被认为 equal 2413 | // [1, 2, 3], [1, 2, 3] 被认为 equal 2414 | // 0 和 -0 被认为 unequal 2415 | // NaN 和 NaN 被认为 equal 2416 | _.isEqual = function(a, b) { 2417 | return eq(a, b); 2418 | }; 2419 | 2420 | // Is a given array, string, or object empty? 2421 | // An "empty" object has no enumerable own-properties. 2422 | // 是否是 {}、[] 或者 "" 或者 null、undefined 2423 | _.isEmpty = function(obj) { 2424 | if (obj == null) return true; 2425 | 2426 | // 如果是数组、类数组、或者字符串 2427 | // 根据 length 属性判断是否为空 2428 | // 后面的条件是为了过滤 isArrayLike 对于 {length: 10} 这样对象的判断 bug? 2429 | if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0; 2430 | 2431 | // 如果是对象 2432 | // 根据 keys 数量判断是否为 Empty 2433 | return _.keys(obj).length === 0; 2434 | }; 2435 | 2436 | 2437 | // Is a given value a DOM element? 2438 | // 判断是否为 DOM 元素 2439 | _.isElement = function(obj) { 2440 | // 确保 obj 不是 null, undefined 等假值 2441 | // 并且 obj.nodeType === 1 2442 | return !!(obj && obj.nodeType === 1); 2443 | }; 2444 | 2445 | // Is a given value an array? 2446 | // Delegates to ECMA5's native Array.isArray 2447 | // 判断是否为数组 2448 | _.isArray = nativeIsArray || function(obj) { 2449 | return toString.call(obj) === '[object Array]'; 2450 | }; 2451 | 2452 | // Is a given variable an object? 2453 | // 判断是否为对象 2454 | // 这里的对象包括 function 和 object 2455 | _.isObject = function(obj) { 2456 | var type = typeof obj; 2457 | return type === 'function' || type === 'object' && !!obj; 2458 | }; 2459 | 2460 | // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError. 2461 | // 其他类型判断 2462 | _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) { 2463 | _['is' + name] = function(obj) { 2464 | return toString.call(obj) === '[object ' + name + ']'; 2465 | }; 2466 | }); 2467 | 2468 | // Define a fallback version of the method in browsers (ahem, IE < 9), where 2469 | // there isn't any inspectable "Arguments" type. 2470 | // _.isArguments 方法在 IE < 9 下的兼容 2471 | // IE < 9 下对 arguments 调用 Object.prototype.toString.call 方法 2472 | // 结果是 => [object Object] 2473 | // 而并非我们期望的 [object Arguments]。 2474 | // so 用是否含有 callee 属性来做兼容 2475 | if (!_.isArguments(arguments)) { 2476 | _.isArguments = function(obj) { 2477 | return _.has(obj, 'callee'); 2478 | }; 2479 | } 2480 | 2481 | // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8, 2482 | // IE 11 (#1621), and in Safari 8 (#1929). 2483 | // _.isFunction 在 old v8, IE 11 和 Safari 8 下的兼容 2484 | // 觉得这里有点问题 2485 | // 我用的 chrome 49 (显然不是 old v8) 2486 | // 却也进入了这个 if 判断内部 2487 | if (typeof /./ != 'function' && typeof Int8Array != 'object') { 2488 | _.isFunction = function(obj) { 2489 | return typeof obj == 'function' || false; 2490 | }; 2491 | } 2492 | 2493 | // Is a given object a finite number? 2494 | // 判断是否是有限的数字 2495 | _.isFinite = function(obj) { 2496 | return isFinite(obj) && !isNaN(parseFloat(obj)); 2497 | }; 2498 | 2499 | // Is the given value `NaN`? (NaN is the only number which does not equal itself). 2500 | // 判断是否是 NaN 2501 | // NaN 是唯一的一个 `自己不等于自己` 的 number 类型 2502 | // 这样写有 BUG 2503 | // _.isNaN(new Number(0)) => true 2504 | // 详见 https://github.com/hanzichi/underscore-analysis/issues/13 2505 | // 最新版本(edge 版)已经修复该 BUG 2506 | _.isNaN = function(obj) { 2507 | return _.isNumber(obj) && obj !== +obj; 2508 | }; 2509 | 2510 | // Is a given value a boolean? 2511 | // 判断是否是布尔值 2512 | // 基础类型(true、 false) 2513 | // 以及 new Boolean() 两个方向判断 2514 | // 有点多余了吧? 2515 | // 个人觉得直接用 toString.call(obj) 来判断就可以了 2516 | _.isBoolean = function(obj) { 2517 | return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; 2518 | }; 2519 | 2520 | // Is a given value equal to null? 2521 | // 判断是否是 null 2522 | _.isNull = function(obj) { 2523 | return obj === null; 2524 | }; 2525 | 2526 | // Is a given variable undefined? 2527 | // 判断是否是 undefined 2528 | // undefined 能被改写 (IE < 9) 2529 | // undefined 只是全局对象的一个属性 2530 | // 在局部环境能被重新定义 2531 | // 但是「void 0」始终是 undefined 2532 | _.isUndefined = function(obj) { 2533 | return obj === void 0; 2534 | }; 2535 | 2536 | // Shortcut function for checking if an object has a given property directly 2537 | // on itself (in other words, not on a prototype). 2538 | // 判断对象中是否有指定 key 2539 | // own properties, not on a prototype 2540 | _.has = function(obj, key) { 2541 | // obj 不能为 null 或者 undefined 2542 | return obj != null && hasOwnProperty.call(obj, key); 2543 | }; 2544 | 2545 | 2546 | // Utility Functions 2547 | // 工具类方法 2548 | // 共 14 个扩展方法 2549 | // ----------------- 2550 | 2551 | // Run Underscore.js in *noConflict* mode, returning the `_` variable to its 2552 | // previous owner. Returns a reference to the Underscore object. 2553 | // 如果全局环境中已经使用了 `_` 变量 2554 | // 可以用该方法返回其他变量 2555 | // 继续使用 underscore 中的方法 2556 | // var underscore = _.noConflict(); 2557 | // underscore.each(..); 2558 | _.noConflict = function() { 2559 | root._ = previousUnderscore; 2560 | return this; 2561 | }; 2562 | 2563 | // Keep the identity function around for default iteratees. 2564 | // 返回传入的参数,看起来好像没什么卵用 2565 | // 其实 _.identity 在 undescore 内大量作为迭代函数出现 2566 | // 能简化很多迭代函数的书写 2567 | _.identity = function(value) { 2568 | return value; 2569 | }; 2570 | 2571 | // Predicate-generating functions. Often useful outside of Underscore. 2572 | _.constant = function(value) { 2573 | return function() { 2574 | return value; 2575 | }; 2576 | }; 2577 | 2578 | _.noop = function(){}; 2579 | 2580 | // 传送门 2581 | /* 2582 | var property = function(key) { 2583 | return function(obj) { 2584 | return obj == null ? void 0 : obj[key]; 2585 | }; 2586 | }; 2587 | */ 2588 | _.property = property; 2589 | 2590 | // Generates a function for a given object that returns a given property. 2591 | _.propertyOf = function(obj) { 2592 | return obj == null ? function(){} : function(key) { 2593 | return obj[key]; 2594 | }; 2595 | }; 2596 | 2597 | // Returns a predicate for checking whether an object has a given set of 2598 | // `key:value` pairs. 2599 | // 判断一个给定的对象是否有某些键值对 2600 | _.matcher = _.matches = function(attrs) { 2601 | attrs = _.extendOwn({}, attrs); 2602 | return function(obj) { 2603 | return _.isMatch(obj, attrs); 2604 | }; 2605 | }; 2606 | 2607 | // Run a function **n** times. 2608 | // 执行某函数 n 次 2609 | _.times = function(n, iteratee, context) { 2610 | var accum = Array(Math.max(0, n)); 2611 | iteratee = optimizeCb(iteratee, context, 1); 2612 | for (var i = 0; i < n; i++) 2613 | accum[i] = iteratee(i); 2614 | return accum; 2615 | }; 2616 | 2617 | // Return a random integer between min and max (inclusive). 2618 | // 返回一个 [min, max] 范围内的任意整数 2619 | _.random = function(min, max) { 2620 | if (max == null) { 2621 | max = min; 2622 | min = 0; 2623 | } 2624 | return min + Math.floor(Math.random() * (max - min + 1)); 2625 | }; 2626 | 2627 | // A (possibly faster) way to get the current timestamp as an integer. 2628 | // 返回当前时间的 "时间戳"(单位 ms) 2629 | // 其实并不是时间戳,时间戳还要除以 1000(单位 s) 2630 | // +new Date 类似 2631 | _.now = Date.now || function() { 2632 | return new Date().getTime(); 2633 | }; 2634 | 2635 | // List of HTML entities for escaping. 2636 | // HTML 实体编码 2637 | // escapeMap 用于编码 2638 | // see @http://www.cnblogs.com/zichi/p/5135636.html 2639 | // in PHP, htmlspecialchars — Convert special characters to HTML entities 2640 | // see @http://php.net/manual/zh/function.htmlspecialchars.php 2641 | // 能将 & " ' < > 转为实体编码(下面的前 5 种) 2642 | var escapeMap = { 2643 | '&': '&', 2644 | '<': '<', 2645 | '>': '>', 2646 | '"': '"', 2647 | // 以上四个为最常用的字符实体 2648 | // 也是仅有的可以在所有环境下使用的实体字符(其他应该用「实体数字」,如下) 2649 | // 浏览器也许并不支持所有实体名称(对实体数字的支持却很好) 2650 | "'": ''', 2651 | '`': '`' 2652 | }; 2653 | 2654 | // _.invert 方法将一个对象的键值对对调 2655 | // unescapeMap 用于解码 2656 | var unescapeMap = _.invert(escapeMap); 2657 | 2658 | // Functions for escaping and unescaping strings to/from HTML interpolation. 2659 | var createEscaper = function(map) { 2660 | var escaper = function(match) { 2661 | return map[match]; 2662 | }; 2663 | // Regexes for identifying a key that needs to be escaped 2664 | // 正则替换 2665 | // 注意下 ?: 2666 | var source = '(?:' + _.keys(map).join('|') + ')'; 2667 | 2668 | // 正则 pattern 2669 | var testRegexp = RegExp(source); 2670 | 2671 | // 全局替换 2672 | var replaceRegexp = RegExp(source, 'g'); 2673 | return function(string) { 2674 | string = string == null ? '' : '' + string; 2675 | return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; 2676 | }; 2677 | }; 2678 | 2679 | // Escapes a string for insertion into HTML, replacing &, <, >, ", `, and ' characters. 2680 | // 编码,防止被 XSS 攻击等一些安全隐患 2681 | _.escape = createEscaper(escapeMap); 2682 | 2683 | // The opposite of escape 2684 | // replaces &, <, >, ", ` and ' with their unescaped counterparts 2685 | // 解码 2686 | _.unescape = createEscaper(unescapeMap); 2687 | 2688 | // If the value of the named `property` is a function then invoke it with the 2689 | // `object` as context; otherwise, return it. 2690 | _.result = function(object, property, fallback) { 2691 | var value = object == null ? void 0 : object[property]; 2692 | if (value === void 0) { 2693 | value = fallback; 2694 | } 2695 | return _.isFunction(value) ? value.call(object) : value; 2696 | }; 2697 | 2698 | // Generate a unique integer id (unique within the entire client session). 2699 | // Useful for temporary DOM ids. 2700 | // 生成客户端临时的 DOM ids 2701 | var idCounter = 0; 2702 | _.uniqueId = function(prefix) { 2703 | var id = ++idCounter + ''; 2704 | return prefix ? prefix + id : id; 2705 | }; 2706 | 2707 | // By default, Underscore uses ERB-style template delimiters, change the 2708 | // following template settings to use alternative delimiters. 2709 | // ERB => Embedded Ruby 2710 | // Underscore 默认采用 ERB-style 风格模板,也可以根据自己习惯自定义模板 2711 | // 1. <% %> - to execute some code 2712 | // 2. <%= %> - to print some value in template 2713 | // 3. <%- %> - to print some values HTML escaped 2714 | _.templateSettings = { 2715 | // 三种渲染模板 2716 | evaluate : /<%([\s\S]+?)%>/g, 2717 | interpolate : /<%=([\s\S]+?)%>/g, 2718 | escape : /<%-([\s\S]+?)%>/g 2719 | }; 2720 | 2721 | // When customizing `templateSettings`, if you don't want to define an 2722 | // interpolation, evaluation or escaping regex, we need one that is 2723 | // guaranteed not to match. 2724 | var noMatch = /(.)^/; 2725 | 2726 | // Certain characters need to be escaped so that they can be put into a 2727 | // string literal. 2728 | var escapes = { 2729 | "'": "'", 2730 | '\\': '\\', 2731 | '\r': 'r', // 回车符 2732 | '\n': 'n', // 换行符 2733 | // http://stackoverflow.com/questions/16686687/json-stringify-and-u2028-u2029-check 2734 | '\u2028': 'u2028', // Line separator 2735 | '\u2029': 'u2029' // Paragraph separator 2736 | }; 2737 | 2738 | // RegExp pattern 2739 | var escaper = /\\|'|\r|\n|\u2028|\u2029/g; 2740 | 2741 | var escapeChar = function(match) { 2742 | /** 2743 | ' => \\' 2744 | \\ => \\\\ 2745 | \r => \\r 2746 | \n => \\n 2747 | \u2028 => \\u2028 2748 | \u2029 => \\u2029 2749 | **/ 2750 | return '\\' + escapes[match]; 2751 | }; 2752 | 2753 | // 将 JavaScript 模板编译为可以用于页面呈现的函数 2754 | // JavaScript micro-templating, similar to John Resig's implementation. 2755 | // Underscore templating handles arbitrary delimiters, preserves whitespace, 2756 | // and correctly escapes quotes within interpolated code. 2757 | // NB: `oldSettings` only exists for backwards compatibility. 2758 | // oldSettings 参数为了兼容 underscore 旧版本 2759 | // setting 参数可以用来自定义字符串模板(但是 key 要和 _.templateSettings 中的相同,才能 overridden) 2760 | // 1. <% %> - to execute some code 2761 | // 2. <%= %> - to print some value in template 2762 | // 3. <%- %> - to print some values HTML escaped 2763 | // Compiles JavaScript templates into functions 2764 | // _.template(templateString, [settings]) 2765 | _.template = function(text, settings, oldSettings) { 2766 | // 兼容旧版本 2767 | if (!settings && oldSettings) 2768 | settings = oldSettings; 2769 | 2770 | // 相同的 key,优先选择 settings 对象中的 2771 | // 其次选择 _.templateSettings 对象中的 2772 | // 生成最终用来做模板渲染的字符串 2773 | // 自定义模板优先于默认模板 _.templateSettings 2774 | // 如果定义了相同的 key,则前者会覆盖后者 2775 | settings = _.defaults({}, settings, _.templateSettings); 2776 | 2777 | // Combine delimiters into one regular expression via alternation. 2778 | // 正则表达式 pattern,用于正则匹配 text 字符串中的模板字符串 2779 | // /<%-([\s\S]+?)%>|<%=([\s\S]+?)%>|<%([\s\S]+?)%>|$/g 2780 | // 注意最后还有个 |$ 2781 | var matcher = RegExp([ 2782 | // 注意下 pattern 的 source 属性 2783 | (settings.escape || noMatch).source, 2784 | (settings.interpolate || noMatch).source, 2785 | (settings.evaluate || noMatch).source 2786 | ].join('|') + '|$', 'g'); 2787 | 2788 | // Compile the template source, escaping string literals appropriately. 2789 | // 编译模板字符串,将原始的模板字符串替换成函数字符串 2790 | // 用拼接成的函数字符串生成函数(new Function(...)) 2791 | var index = 0; 2792 | 2793 | // source 变量拼接的字符串用来生成函数 2794 | // 用于当做 new Function 生成函数时的函数字符串变量 2795 | // 记录编译成的函数字符串,可通过 _.template(tpl).source 获取(_.template(tpl) 返回方法) 2796 | var source = "__p+='"; 2797 | 2798 | // replace 函数不需要为返回值赋值,主要是为了在函数内对 source 变量赋值 2799 | // 将 text 变量中的模板提取出来 2800 | // match 为匹配的整个串 2801 | // escape/interpolate/evaluate 为匹配的子表达式(如果没有匹配成功则为 undefined) 2802 | // offset 为字符匹配(match)的起始位置(偏移量) 2803 | text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { 2804 | // \n => \\n 2805 | source += text.slice(index, offset).replace(escaper, escapeChar); 2806 | // 改变 index 值,为了下次的 slice 2807 | index = offset + match.length; 2808 | 2809 | if (escape) { 2810 | // 需要对变量进行编码(=> HTML 实体编码) 2811 | // 避免 XSS 攻击 2812 | source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; 2813 | } else if (interpolate) { 2814 | // 单纯的插入变量 2815 | source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; 2816 | } else if (evaluate) { 2817 | // 可以直接执行的 JavaScript 语句 2818 | // 注意 "__p+=",__p 为渲染返回的字符串 2819 | source += "';\n" + evaluate + "\n__p+='"; 2820 | } 2821 | // Adobe VMs need the match returned to produce the correct offset. 2822 | // return 的作用是? 2823 | // 将匹配到的内容原样返回(Adobe VMs 需要返回 match 来使得 offset 值正常) 2824 | return match; 2825 | }); 2826 | 2827 | source += "';\n"; 2828 | // By default, `template` places the values from your data in the local scope via the `with` statement. 2829 | // However, you can specify a single variable name with the variable setting. 2830 | // This can significantly improve the speed at which a template is able to render. 2831 | // If a variable is not specified, place data values in local scope. 2832 | // 指定 scope 2833 | // 如果设置了 settings.variable,能显著提升模板的渲染速度 2834 | // 否则,默认用 with 语句指定作用域 2835 | if (!settings.variable) 2836 | source = 'with(obj||{}){\n' + source + '}\n'; 2837 | 2838 | // 增加 print 功能 2839 | // __p 为返回的字符串 2840 | source = "var __t,__p='',__j=Array.prototype.join," + 2841 | "print=function(){__p+=__j.call(arguments,'');};\n" + 2842 | source + 'return __p;\n'; 2843 | 2844 | try { 2845 | // render 方法,前两个参数为 render 方法的参数 2846 | // obj 为传入的 JSON 对象,传入 _ 参数使得函数内部能用 Underscore 的函数 2847 | var render = new Function(settings.variable || 'obj', '_', source); 2848 | } catch (e) { 2849 | // 抛出错误 2850 | e.source = source; 2851 | throw e; 2852 | } 2853 | 2854 | // 返回的函数 2855 | // data 一般是 JSON 数据,用来渲染模板 2856 | var template = function(data) { 2857 | // render 为模板渲染函数 2858 | // 传入参数 _ ,使得模板里 <% %> 里的代码能用 underscore 的方法 2859 | //(<% %> - to execute some code) 2860 | return render.call(this, data, _); 2861 | }; 2862 | 2863 | // Provide the compiled source as a convenience for precompilation. 2864 | // template.source for debug? 2865 | // obj 与 with(obj||{}) 中的 obj 对应 2866 | var argument = settings.variable || 'obj'; 2867 | 2868 | // 可通过 _.template(tpl).source 获取 2869 | // 可以用来预编译,在服务端预编译好,直接在客户端生成代码,客户端直接调用方法 2870 | // 这样如果出错就能打印出错行 2871 | // Precompiling your templates can be a big help when debugging errors you can't reproduce. 2872 | // This is because precompiled templates can provide line numbers and a stack trace, 2873 | // something that is not possible when compiling templates on the client. 2874 | // The source property is available on the compiled template function for easy precompilation. 2875 | // see @http://stackoverflow.com/questions/18755292/underscore-js-precompiled-templates-using 2876 | // see @http://stackoverflow.com/questions/13536262/what-is-javascript-template-precompiling 2877 | // see @http://stackoverflow.com/questions/40126223/can-anyone-explain-underscores-precompilation-in-template 2878 | // JST is a server-side thing, not client-side. 2879 | // This mean that you compile Unserscore template on server side by some server-side script and save the result in a file. 2880 | // Then use this file as compiled Unserscore template. 2881 | template.source = 'function(' + argument + '){\n' + source + '}'; 2882 | 2883 | return template; 2884 | }; 2885 | 2886 | // Add a "chain" function. Start chaining a wrapped Underscore object. 2887 | // 使支持链式调用 2888 | /** 2889 | // 非 OOP 调用 chain 2890 | _.chain([1, 2, 3]) 2891 | .map(function(a) { return a * 2; }) 2892 | .reverse().value(); // [6, 4, 2] 2893 | // OOP 调用 chain 2894 | _([1, 2, 3]) 2895 | .chain() 2896 | .map(function(a){ return a * 2; }) 2897 | .first() 2898 | .value(); // 2 2899 | **/ 2900 | _.chain = function(obj) { 2901 | // 无论是否 OOP 调用,都会转为 OOP 形式 2902 | // 并且给新的构造对象添加了一个 _chain 属性 2903 | var instance = _(obj); 2904 | 2905 | // 标记是否使用链式操作 2906 | instance._chain = true; 2907 | 2908 | // 返回 OOP 对象 2909 | // 可以看到该 instance 对象除了多了个 _chain 属性 2910 | // 其他的和直接 _(obj) 的结果一样 2911 | return instance; 2912 | }; 2913 | 2914 | // OOP 2915 | // --------------- 2916 | // If Underscore is called as a function, it returns a wrapped object that 2917 | // can be used OO-style. This wrapper holds altered versions of all the 2918 | // underscore functions. Wrapped objects may be chained. 2919 | 2920 | // OOP 2921 | // 如果 `_` 被当做方法(构造函数)调用, 则返回一个被包装过的对象 2922 | // 该对象能使用 underscore 的所有方法 2923 | // 并且支持链式调用 2924 | 2925 | // Helper function to continue chaining intermediate results. 2926 | // 一个帮助方法(Helper function) 2927 | var result = function(instance, obj) { 2928 | // 如果需要链式操作,则对 obj 运行 _.chain 方法,使得可以继续后续的链式操作 2929 | // 如果不需要,直接返回 obj 2930 | return instance._chain ? _(obj).chain() : obj; 2931 | }; 2932 | 2933 | // Add your own custom functions to the Underscore object. 2934 | // 可向 underscore 函数库扩展自己的方法 2935 | // obj 参数必须是一个对象(JavaScript 中一切皆对象) 2936 | // 且自己的方法定义在 obj 的属性上 2937 | // 如 obj.myFunc = function() {...} 2938 | // 形如 {myFunc: function(){}} 2939 | // 之后便可使用如下: _.myFunc(..) 或者 OOP _(..).myFunc(..) 2940 | _.mixin = function(obj) { 2941 | // 遍历 obj 的 key,将方法挂载到 Underscore 上 2942 | // 其实是将方法浅拷贝到 _.prototype 上 2943 | _.each(_.functions(obj), function(name) { 2944 | // 直接把方法挂载到 _[name] 上 2945 | // 调用类似 _.myFunc([1, 2, 3], ..) 2946 | var func = _[name] = obj[name]; 2947 | 2948 | // 浅拷贝 2949 | // 将 name 方法挂载到 _ 对象的原型链上,使之能 OOP 调用 2950 | _.prototype[name] = function() { 2951 | // 第一个参数 2952 | var args = [this._wrapped]; 2953 | 2954 | // arguments 为 name 方法需要的其他参数 2955 | push.apply(args, arguments); 2956 | // 执行 func 方法 2957 | // 支持链式操作 2958 | return result(this, func.apply(_, args)); 2959 | }; 2960 | }); 2961 | }; 2962 | 2963 | // Add all of the Underscore functions to the wrapper object. 2964 | // 将前面定义的 underscore 方法添加给包装过的对象 2965 | // 即添加到 _.prototype 中 2966 | // 使 underscore 支持面向对象形式的调用 2967 | _.mixin(_); 2968 | 2969 | // Add all mutator Array functions to the wrapper. 2970 | // 将 Array 原型链上有的方法都添加到 underscore 中 2971 | _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { 2972 | var method = ArrayProto[name]; 2973 | _.prototype[name] = function() { 2974 | var obj = this._wrapped; 2975 | method.apply(obj, arguments); 2976 | 2977 | if ((name === 'shift' || name === 'splice') && obj.length === 0) 2978 | delete obj[0]; 2979 | 2980 | // 支持链式操作 2981 | return result(this, obj); 2982 | }; 2983 | }); 2984 | 2985 | // Add all accessor Array functions to the wrapper. 2986 | // 添加 concat、join、slice 等数组原生方法给 Underscore 2987 | _.each(['concat', 'join', 'slice'], function(name) { 2988 | var method = ArrayProto[name]; 2989 | _.prototype[name] = function() { 2990 | return result(this, method.apply(this._wrapped, arguments)); 2991 | }; 2992 | }); 2993 | 2994 | // Extracts the result from a wrapped and chained object. 2995 | // 一个包装过(OOP)并且链式调用的对象 2996 | // 用 value 方法获取结果 2997 | // _(obj).value === obj? 2998 | _.prototype.value = function() { 2999 | return this._wrapped; 3000 | }; 3001 | 3002 | // Provide unwrapping proxy for some methods used in engine operations 3003 | // such as arithmetic and JSON stringification. 3004 | _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; 3005 | 3006 | _.prototype.toString = function() { 3007 | return '' + this._wrapped; 3008 | }; 3009 | 3010 | // AMD registration happens at the end for compatibility with AMD loaders 3011 | // that may not enforce next-turn semantics on modules. Even though general 3012 | // practice for AMD registration is to be anonymous, underscore registers 3013 | // as a named module because, like jQuery, it is a base library that is 3014 | // popular enough to be bundled in a third party lib, but not be part of 3015 | // an AMD load request. Those cases could generate an error when an 3016 | // anonymous define() is called outside of a loader request. 3017 | // 兼容 AMD 规范 3018 | if (typeof define === 'function' && define.amd) { 3019 | define('underscore', [], function() { 3020 | return _; 3021 | }); 3022 | } 3023 | }.call(this)); --------------------------------------------------------------------------------