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