// Underscore.js 1.8.3 // http://underscorejs.org // (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. // 中文註釋 by hanzichi @https://github.com/hanzichi // 個人源碼解讀順序(跟系列解讀文章相對應) // Object -> Array -> Collection -> Function -> Utility (function() { // Baseline setup // 基本設置、配置 // -------------- // Establish the root object, `window` in the browser, or `exports` on the server. // 將 this 賦值給局部變量 root // root 的值, 客戶端爲 `window`, 服務端(node) 中爲 `exports` var root = this; // Save the previous value of the `_` variable. // 將原來全局環境中的變量 `_` 賦值給變量 previousUnderscore 進行緩存 // 在後面的 noConflict 方法中有用到 var previousUnderscore = root._; // Save bytes in the minified (but not gzipped) version: // 緩存變量, 便於壓縮代碼 // 此處「壓縮」指的是壓縮到 min.js 版本 // 而不是 gzip 壓縮 var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. // 緩存變量, 便於壓縮代碼 // 同時可減小在原型鏈中的查找次數(提升代碼效率) var push = ArrayProto.push, slice = ArrayProto.slice, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. // ES5 原生方法, 若是瀏覽器支持, 則 underscore 中會優先使用 var nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind, nativeCreate = Object.create; // Naked function reference for surrogate-prototype-swapping. var Ctor = function(){}; // Create a safe reference to the Underscore object for use below. // 核心函數 // `_` 實際上是一個構造函數 // 支持無 new 調用的構造函數(思考 jQuery 的無 new 調用) // 將傳入的參數(實際要操做的數據)賦值給 this._wrapped 屬性 // OOP 調用時,_ 至關於一個構造函數 // each 等方法都在該構造函數的原型鏈上 // _([1, 2, 3]).each(alert) // _([1, 2, 3]) 至關於無 new 構造了一個新的對象 // 調用了該對象的 each 方法,該方法在該對象構造函數的原型鏈上 var _ = function(obj) { // 如下均針對 OOP 形式的調用 // 若是是非 OOP 形式的調用,不會進入該函數內部 // 若是 obj 已是 `_` 函數的實例,則直接返回 obj if (obj instanceof _) return obj; // 若是不是 `_` 函數的實例 // 則調用 new 運算符,返回實例化的對象 if (!(this instanceof _)) return new _(obj); // 將 obj 賦值給 this._wrapped 屬性 this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object. // 將上面定義的 `_` 局部變量賦值給全局對象中的 `_` 屬性 // 即客戶端中 window._ = _ // 服務端(node)中 exports._ = _ // 同時在服務端向後兼容老的 require() API // 這樣暴露給全局後即可以在全局環境中使用 `_` 變量(方法) if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. // 當前 underscore 版本號 _.VERSION = '1.8.3'; // Internal function that returns an efficient (for current engines) version // of the passed-in callback, to be repeatedly applied in other Underscore // functions. // underscore 內部方法 // 根據 this 指向(context 參數) // 以及 argCount 參數 // 二次操做返回一些回調、迭代方法 var optimizeCb = function(func, context, argCount) { // 若是沒有指定 this 指向,則返回原函數 if (context === void 0) return func; switch (argCount == null ? 3 : argCount) { case 1: return function(value) { return func.call(context, value); }; case 2: return function(value, other) { return func.call(context, value, other); }; // 若是有指定 this,但沒有傳入 argCount 參數 // 則執行如下 case // _.each、_.map case 3: return function(value, index, collection) { return func.call(context, value, index, collection); }; // _.reduce、_.reduceRight case 4: return function(accumulator, value, index, collection) { return func.call(context, accumulator, value, index, collection); }; } // 其實不用上面的 switch-case 語句 // 直接執行下面的 return 函數就好了 // 不這樣作的緣由是 call 比 apply 快不少 // .apply 在運行前要對做爲參數的數組進行一系列檢驗和深拷貝,.call 則沒有這些步驟 // 具體能夠參考: // https://segmentfault.com/q/1010000007894513 // http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.4.3 // http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.4.4 return function() { return func.apply(context, arguments); }; }; // A mostly-internal function to generate callbacks that can be applied // to each element in a collection, returning the desired result — either // identity, an arbitrary callback, a property matcher, or a property accessor. var cb = function(value, context, argCount) { if (value == null) return _.identity; if (_.isFunction(value)) return optimizeCb(value, context, argCount); if (_.isObject(value)) return _.matcher(value); return _.property(value); }; _.iteratee = function(value, context) { return cb(value, context, Infinity); }; // An internal function for creating assigner functions. // 有三個方法用到了這個內部函數 // _.extend & _.extendOwn & _.defaults // _.extend = createAssigner(_.allKeys); // _.extendOwn = _.assign = createAssigner(_.keys); // _.defaults = createAssigner(_.allKeys, true); var createAssigner = function(keysFunc, undefinedOnly) { // 返回函數 // 經典閉包(undefinedOnly 參數在返回的函數中被引用) // 返回的函數參數個數 >= 1 // 將第二個開始的對象參數的鍵值對 "繼承" 給第一個參數 return function(obj) { var length = arguments.length; // 只傳入了一個參數(或者 0 個?) // 或者傳入的第一個參數是 null if (length < 2 || obj == null) return obj; // 枚舉第一個參數除外的對象參數 // 即 arguments[1], arguments[2] ... for (var index = 1; index < length; index++) { // source 即爲對象參數 var source = arguments[index], // 提取對象參數的 keys 值 // keysFunc 參數表示 _.keys // 或者 _.allKeys keys = keysFunc(source), l = keys.length; // 遍歷該對象的鍵值對 for (var i = 0; i < l; i++) { var key = keys[i]; // _.extend 和 _.extendOwn 方法 // 沒有傳入 undefinedOnly 參數,即 !undefinedOnly 爲 true // 即確定會執行 obj[key] = source[key] // 後面對象的鍵值對直接覆蓋 obj // ========================================== // _.defaults 方法,undefinedOnly 參數爲 true // 即 !undefinedOnly 爲 false // 那麼當且僅當 obj[key] 爲 undefined 時才覆蓋 // 即若是有相同的 key 值,取最先出現的 value 值 // *defaults 中有相同 key 的也是同樣取首次出現的 if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key]; } } // 返回已經繼承後面對象參數屬性的第一個參數對象 return obj; }; }; // An internal function for creating a new object that inherits from another. // use in `_.create` var baseCreate = function(prototype) { // 若是 prototype 參數不是對象 if (!_.isObject(prototype)) return {}; // 若是瀏覽器支持 ES5 Object.create if (nativeCreate) return nativeCreate(prototype); Ctor.prototype = prototype; var result = new Ctor; Ctor.prototype = null; return result; }; // 閉包 var property = function(key) { return function(obj) { return obj == null ? void 0 : obj[key]; }; }; // Helper for collection methods to determine whether a collection // should be iterated as an array or as an object // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 // Math.pow(2, 53) - 1 是 JavaScript 中能精確表示的最大數字 var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; // getLength 函數 // 該函數傳入一個參數,返回參數的 length 屬性值 // 用來獲取 array 以及 arrayLike 元素的 length 屬性值 var getLength = property('length'); // 判斷是不是 ArrayLike Object // 類數組,即擁有 length 屬性而且 length 屬性值爲 Number 類型的元素 // 包括數組、arguments、HTML Collection 以及 NodeList 等等 // 包括相似 {length: 10} 這樣的對象 // 包括字符串、函數等 var isArrayLike = function(collection) { // 返回參數 collection 的 length 屬性值 var length = getLength(collection); return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; }; // Collection Functions // 數組或者對象的擴展方法 // 共 25 個擴展方法 // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles raw objects in addition to array-likes. Treats all // sparse array-likes as if they were dense. // 與 ES5 中 Array.prototype.forEach 使用方法相似 // 遍歷數組或者對象的每一個元素 // 第一個參數爲數組(包括類數組)或者對象 // 第二個參數爲迭代方法,對數組或者對象每一個元素都執行該方法 // 該方法又能傳入三個參數,分別爲 (item, index, array)((value, key, obj) for object) // 與 ES5 中 Array.prototype.forEach 方法傳參格式一致 // 第三個參數(可省略)肯定第二個參數 iteratee 函數中的(可能有的)this 指向 // 即 iteratee 中出現的(若是有)全部 this 都指向 context // notice: 不要傳入一個帶有 key 類型爲 number 的對象! // notice: _.each 方法不能用 return 跳出循環(一樣,Array.prototype.forEach 也不行) _.each = _.forEach = function(obj, iteratee, context) { // 根據 context 肯定不一樣的迭代函數 iteratee = optimizeCb(iteratee, context); var i, length; // 若是是類數組 // 默認不會傳入相似 {length: 10} 這樣的數據 if (isArrayLike(obj)) { // 遍歷 for (i = 0, length = obj.length; i < length; i++) { iteratee(obj[i], i, obj); } } else { // 若是 obj 是對象 // 獲取對象的全部 key 值 var keys = _.keys(obj); // 若是是對象,則遍歷處理 values 值 for (i = 0, length = keys.length; i < length; i++) { iteratee(obj[keys[i]], keys[i], obj); // (value, key, obj) } } // 返回 obj 參數 // 供鏈式調用(Returns the list for chaining) // 應該僅 OOP 調用有效 return obj; }; // Return the results of applying the iteratee to each element. // 與 ES5 中 Array.prototype.map 使用方法相似 // 傳參形式與 _.each 方法相似 // 遍歷數組(每一個元素)或者對象的每一個元素(value) // 對每一個元素執行 iteratee 迭代方法 // 將結果保存到新的數組中,並返回 _.map = _.collect = function(obj, iteratee, context) { // 根據 context 肯定不一樣的迭代函數 iteratee = cb(iteratee, context); // 若是傳參是對象,則獲取它的 keys 值數組(短路表達式) var keys = !isArrayLike(obj) && _.keys(obj), // 若是 obj 爲對象,則 length 爲 key.length // 若是 obj 爲數組,則 length 爲 obj.length length = (keys || obj).length, results = Array(length); // 結果數組 // 遍歷 for (var index = 0; index < length; index++) { // 若是 obj 爲對象,則 currentKey 爲對象鍵值 key // 若是 obj 爲數組,則 currentKey 爲 index 值 var currentKey = keys ? keys[index] : index; results[index] = iteratee(obj[currentKey], currentKey, obj); } // 返回新的結果數組 return results; }; // Create a reducing function iterating left or right. // dir === 1 -> _.reduce // dir === -1 -> _.reduceRight function createReduce(dir) { // Optimized iterator function as using arguments.length // in the main function will deoptimize the, see #1991. function iterator(obj, iteratee, memo, keys, index, length) { for (; index >= 0 && index < length; index += dir) { var currentKey = keys ? keys[index] : index; // 迭代,返回值供下次迭代調用 memo = iteratee(memo, obj[currentKey], currentKey, obj); } // 每次迭代返回值,供下次迭代調用 return memo; } // _.reduce(_.reduceRight)可傳入的 4 個參數 // obj 數組或者對象 // iteratee 迭代方法,對數組或者對象每一個元素執行該方法 // memo 初始值,若是有,則從 obj 第一個元素開始迭代 // 若是沒有,則從 obj 第二個元素開始迭代,將第一個元素做爲初始值 // context 爲迭代函數中的 this 指向 return function(obj, iteratee, memo, context) { iteratee = optimizeCb(iteratee, context, 4); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length, index = dir > 0 ? 0 : length - 1; // Determine the initial value if none is provided. // 若是沒有指定初始值 // 則把第一個元素指定爲初始值 if (arguments.length < 3) { memo = obj[keys ? keys[index] : index]; // 根據 dir 肯定是向左仍是向右遍歷 index += dir; } return iterator(obj, iteratee, memo, keys, index, length); }; } // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. // 與 ES5 中 Array.prototype.reduce 使用方法相似 // _.reduce(list, iteratee, [memo], [context]) // _.reduce 方法最多可傳入 4 個參數 // memo 爲初始值,可選 // context 爲指定 iteratee 中 this 指向,可選 _.reduce = _.foldl = _.inject = createReduce(1); // The right-associative version of reduce, also known as `foldr`. // 與 ES5 中 Array.prototype.reduceRight 使用方法相似 _.reduceRight = _.foldr = createReduce(-1); // Return the first value which passes a truth test. Aliased as `detect`. // 尋找數組或者對象中第一個知足條件(predicate 函數返回 true)的元素 // 並返回該元素值 // _.find(list, predicate, [context]) _.find = _.detect = function(obj, predicate, context) { var key; // 若是 obj 是數組,key 爲知足條件的下標 if (isArrayLike(obj)) { key = _.findIndex(obj, predicate, context); } else { // 若是 obj 是對象,key 爲知足條件的元素的 key 值 key = _.findKey(obj, predicate, context); } // 若是該元素存在,則返回該元素 // 若是不存在,則默認返回 undefined(函數沒有返回,即返回 undefined) if (key !== void 0 && key !== -1) return obj[key]; }; // Return all the elements that pass a truth test. // Aliased as `select`. // 與 ES5 中 Array.prototype.filter 使用方法相似 // 尋找數組或者對象中全部知足條件的元素 // 若是是數組,則將 `元素值` 存入數組 // 若是是對象,則將 `value 值` 存入數組 // 返回該數組 // _.filter(list, predicate, [context]) _.filter = _.select = function(obj, predicate, context) { var results = []; // 根據 this 指向,返回 predicate 函數(判斷函數) predicate = cb(predicate, context); // 遍歷每一個元素,若是符合條件則存入數組 _.each(obj, function(value, index, list) { if (predicate(value, index, list)) results.push(value); }); return results; }; // Return all the elements for which a truth test fails. // 尋找數組或者對象中全部不知足條件的元素 // 並以數組方式返回 // 所得結果是 _.filter 方法的補集 _.reject = function(obj, predicate, context) { return _.filter(obj, _.negate(cb(predicate)), context); }; // Determine whether all of the elements match a truth test. // Aliased as `all`. // 與 ES5 中的 Array.prototype.every 方法相似 // 判斷數組中的每一個元素或者對象中每一個 value 值是否都知足 predicate 函數中的判斷條件 // 若是是,則返回 ture;不然返回 false(有一個不知足就返回 false) // _.every(list, [predicate], [context]) _.every = _.all = function(obj, predicate, context) { // 根據 this 指向,返回相應 predicate 函數 predicate = cb(predicate, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; // 若是有一個不能知足 predicate 中的條件 // 則返回 false if (!predicate(obj[currentKey], currentKey, obj)) return false; } return true; }; // Determine if at least one element in the object matches a truth test. // Aliased as `any`. // 與 ES5 中 Array.prototype.some 方法相似 // 判斷數組或者對象中是否有一個元素(value 值 for object)知足 predicate 函數中的條件 // 若是是則返回 true;不然返回 false // _.some(list, [predicate], [context]) _.some = _.any = function(obj, predicate, context) { // 根據 context 返回 predicate 函數 predicate = cb(predicate, context); // 若是傳參是對象,則返回該對象的 keys 數組 var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; // 若是有一個元素知足條件,則返回 true if (predicate(obj[currentKey], currentKey, obj)) return true; } return false; }; // Determine if the array or object contains a given item (using `===`). // Aliased as `includes` and `include`. // 判斷數組或者對象中(value 值)是否有指定元素 // 若是是 object,則忽略 key 值,只須要查找 value 值便可 // 即該 obj 中是否有指定的 value 值 // 返回布爾值 _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) { // 若是是對象,返回 values 組成的數組 if (!isArrayLike(obj)) obj = _.values(obj); // fromIndex 表示查詢起始位置 // 若是沒有指定該參數,則默認從頭找起 if (typeof fromIndex != 'number' || guard) fromIndex = 0; // _.indexOf 是數組的擴展方法(Array Functions) // 數組中尋找某一元素 return _.indexOf(obj, item, fromIndex) >= 0; }; // Invoke a method (with arguments) on every item in a collection. // Calls the method named by methodName on each value in the list. // Any extra arguments passed to invoke will be forwarded on to the method invocation. // 數組或者對象中的每一個元素都調用 method 方法 // 返回調用後的結果(數組或者關聯數組) // method 參數後的參數會被當作參數傳入 method 方法中 // _.invoke(list, methodName, *arguments) _.invoke = function(obj, method) { // *arguments 參數 var args = slice.call(arguments, 2); // 判斷 method 是否是函數 var isFunc = _.isFunction(method); // 用 map 方法對數組或者對象每一個元素調用方法 // 返回數組 return _.map(obj, function(value) { // 若是 method 不是函數,則多是 obj 的 key 值 // 而 obj[method] 可能爲函數 var func = isFunc ? method : value[method]; return func == null ? func : func.apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. // 一個數組,元素都是對象 // 根據指定的 key 值 // 返回一個數組,元素都是指定 key 值的 value 值 /* var property = function(key) { return function(obj) { return obj == null ? void 0 : obj[key]; }; }; */ // _.pluck(list, propertyName) _.pluck = function(obj, key) { return _.map(obj, _.property(key)); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. // 根據指定的鍵值對 // 選擇對象 _.where = function(obj, attrs) { return _.filter(obj, _.matcher(attrs)); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. // 尋找第一個有指定 key-value 鍵值對的對象 _.findWhere = function(obj, attrs) { return _.find(obj, _.matcher(attrs)); }; // Return the maximum element (or element-based computation). // 尋找數組中的最大元素 // 或者對象中的最大 value 值 // 若是有 iteratee 參數,則求每一個元素通過該函數迭代後的最值 // _.max(list, [iteratee], [context]) _.max = function(obj, iteratee, context) { var result = -Infinity, lastComputed = -Infinity, value, computed; // 單純地尋找最值 if (iteratee == null && obj != null) { // 若是是數組,則尋找數組中最大元素 // 若是是對象,則尋找最大 value 值 obj = isArrayLike(obj) ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value > result) { result = value; } } } else { // 尋找元素通過迭代後的最值 iteratee = cb(iteratee, context); // result 保存結果元素 // lastComputed 保存計算過程當中出現的最值 // 遍歷元素 _.each(obj, function(value, index, list) { // 通過迭代函數後的值 computed = iteratee(value, index, list); // && 的優先級高於 || if (computed > lastComputed || computed === -Infinity && result === -Infinity) { result = value; lastComputed = computed; } }); } return result; }; // Return the minimum element (or element-based computation). // 尋找最小的元素 // 相似 _.max // _.min(list, [iteratee], [context]) _.min = function(obj, iteratee, context) { var result = Infinity, lastComputed = Infinity, value, computed; if (iteratee == null && obj != null) { obj = isArrayLike(obj) ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value < result) { result = value; } } } else { iteratee = cb(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed < lastComputed || computed === Infinity && result === Infinity) { result = value; lastComputed = computed; } }); } return result; }; // Shuffle a collection, using the modern version of the // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). // 將數組亂序 // 若是是對象,則返回一個數組,數組由對象 value 值構成 // Fisher-Yates shuffle 算法 // 最優的洗牌算法,複雜度 O(n) // 亂序不要用 sort + Math.random(),複雜度 O(nlogn) // 並且,並非真正的亂序 // @see https://github.com/hanzichi/underscore-analysis/issues/15 _.shuffle = function(obj) { // 若是是對象,則對 value 值進行亂序 var set = isArrayLike(obj) ? obj : _.values(obj); var length = set.length; // 亂序後返回的數組副本(參數是對象則返回亂序後的 value 數組) var shuffled = Array(length); // 枚舉元素 for (var index = 0, rand; index < length; index++) { // 將當前所枚舉位置的元素和 `index=rand` 位置的元素交換 rand = _.random(0, index); if (rand !== index) shuffled[index] = shuffled[rand]; shuffled[rand] = set[index]; } return shuffled; }; // Sample **n** random values from a collection. // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `map`. // 隨機返回數組或者對象中的一個元素 // 若是指定了參數 `n`,則隨機返回 n 個元素組成的數組 // 若是參數是對象,則數組由 values 組成 _.sample = function(obj, n, guard) { // 隨機返回一個元素 if (n == null || guard) { if (!isArrayLike(obj)) obj = _.values(obj); return obj[_.random(obj.length - 1)]; } // 隨機返回 n 個 return _.shuffle(obj).slice(0, Math.max(0, n)); }; // Sort the object's values by a criterion produced by an iteratee. // 排序 // _.sortBy(list, iteratee, [context]) _.sortBy = function(obj, iteratee, context) { iteratee = cb(iteratee, context); // 根據指定的 key 返回 values 數組 // _.pluck([{}, {}, {}], 'value') return _.pluck( // _.map(obj, function(){}).sort() // _.map 後的結果 [{}, {}..] // sort 後的結果 [{}, {}..] _.map(obj, function(value, index, list) { return { value: value, index: index, // 元素通過迭代函數迭代後的值 criteria: iteratee(value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); }; // An internal function used for aggregate "group by" operations. // behavior 是一個函數參數 // _.groupBy, _.indexBy 以及 _.countBy 其實都是對數組元素進行分類 // 分類規則就是 behavior 函數 var group = function(behavior) { return function(obj, iteratee, context) { // 返回結果是一個對象 var result = {}; iteratee = cb(iteratee, context); // 遍歷元素 _.each(obj, function(value, index) { // 通過迭代,獲取結果值,存爲 key var key = iteratee(value, index, obj); // 按照不一樣的規則進行分組操做 // 將變量 result 當作參數傳入,能在 behavior 中改變該值 behavior(result, value, key); }); // 返回結果對象 return result; }; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. // groupBy_ _.groupBy(list, iteratee, [context]) // 根據特定規則對數組或者對象中的元素進行分組 // result 是返回對象 // value 是數組元素 // key 是迭代後的值 _.groupBy = group(function(result, value, key) { // 根據 key 值分組 // key 是元素通過迭代函數後的值 // 或者元素自身的屬性值 // result 對象已經有該 key 值了 if (_.has(result, key)) result[key].push(value); else result[key] = [value]; }); // Indexes the object's values by a criterion, similar to `groupBy`, but for // when you know that your index values will be unique. _.indexBy = group(function(result, value, key) { // key 值必須是獨一無二的 // 否則後面的會覆蓋前面的 // 其餘和 _.groupBy 相似 result[key] = value; }); // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = group(function(result, value, key) { // 不一樣 key 值元素數量 if (_.has(result, key)) result[key]++; else result[key] = 1; }); // Safely create a real, live array from anything iterable. // 僞數組 -> 數組 // 對象 -> 提取 value 值組成數組 // 返回數組 _.toArray = function(obj) { if (!obj) return []; // 若是是數組,則返回副本數組 // 是否用 obj.concat() 更方便? if (_.isArray(obj)) return slice.call(obj); // 若是是類數組,則從新構造新的數組 // 是否也能夠直接用 slice 方法? if (isArrayLike(obj)) return _.map(obj, _.identity); // 若是是對象,則返回 values 集合 return _.values(obj); }; // Return the number of elements in an object. // 若是是數組(類數組),返回長度(length 屬性) // 若是是對象,返回鍵值對數量 _.size = function(obj) { if (obj == null) return 0; return isArrayLike(obj) ? obj.length : _.keys(obj).length; }; // Split a collection into two arrays: one whose elements all satisfy the given // predicate, and one whose elements all do not satisfy the predicate. // 將數組或者對象中符合條件(predicate)的元素 // 和不符合條件的元素(數組爲元素,對象爲 value 值) // 分別放入兩個數組中 // 返回一個數組,數組元素爲以上兩個數組([[pass array], [fail array]]) _.partition = function(obj, predicate, context) { predicate = cb(predicate, context); var pass = [], fail = []; _.each(obj, function(value, key, obj) { (predicate(value, key, obj) ? pass : fail).push(value); }); return [pass, fail]; }; // Array Functions // 數組的擴展方法 // 共 20 個擴展方法 // Note: All array functions will also work on the arguments object. // However, Underscore functions are not designed to work on "sparse" arrays. // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. // 返回數組第一個元素 // 若是有參數 n,則返回數組前 n 個元素(組成的數組) _.first = _.head = _.take = function(array, n, guard) { // 容錯,數組爲空則返回 undefined if (array == null) return void 0; // 沒指定參數 n,則默認返回第一個元素 if (n == null || guard) return array[0]; // 若是傳入參數 n,則返回前 n 個元素組成的數組 // 返回前 n 個元素,即剔除後 array.length - n 個元素 return _.initial(array, array.length - n); }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. // 傳入一個數組 // 返回剔除最後一個元素以後的數組副本 // 若是傳入參數 n,則剔除最後 n 個元素 _.initial = function(array, n, guard) { return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. // 返回數組最後一個元素 // 若是傳入參數 n // 則返回該數組後 n 個元素組成的數組 // 即剔除前 array.length - n 個元素 _.last = function(array, n, guard) { // 容錯 if (array == null) return void 0; // 若是沒有指定參數 n,則返回最後一個元素 if (n == null || guard) return array[array.length - 1]; // 若是傳入參數 n,則返回後 n 個元素組成的數組 // 即剔除前 array.length - n 個元素 return _.rest(array, Math.max(0, array.length - n)); }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. // 傳入一個數組 // 返回剔除第一個元素後的數組副本 // 若是傳入參數 n,則剔除前 n 個元素 _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, n == null || guard ? 1 : n); }; // Trim out all falsy values from an array. // 去掉數組中全部的假值 // 返回數組副本 // JavaScript 中的假值包括 false、null、undefined、''、NaN、0 // 聯想 PHP 中的 array_filter() 函數 // _.identity = function(value) { // return value; // }; _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. // 遞歸調用數組,將數組展開 // 即 [1, 2, [3, 4]] => [1, 2, 3, 4] // flatten(array, shallow, false) // flatten(arguments, true, true, 1) // flatten(arguments, true, true) // flatten(arguments, false, false, 1) // ===== // // input => Array 或者 arguments // shallow => 是否只展開一層 // strict === true,一般和 shallow === true 配合使用 // 表示只展開一層,可是不保存非數組元素(即沒法展開的基礎類型) // flatten([[1, 2], 3, 4], true, true) => [1, 2] // flatten([[1, 2], 3, 4], false, true) = > [] // startIndex => 從 input 的第幾項開始展開 // ===== // // 能夠看到,若是 strict 參數爲 true,那麼 shallow 也爲 true // 也就是展開一層,同時把非數組過濾 // [[1, 2], [3, 4], 5, 6] => [1, 2, 3, 4] var flatten = function(input, shallow, strict, startIndex) { // output 數組保存結果 // 即 flatten 方法返回數據 // idx 爲 output 的累計數組下標 var output = [], idx = 0; // 根據 startIndex 變量肯定須要展開的起始位置 for (var i = startIndex || 0, length = getLength(input); i < length; i++) { var value = input[i]; // 數組 或者 arguments // 注意 isArrayLike 還包括 {length: 10} 這樣的,過濾掉 if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { // flatten current level of array or arguments object // (!shallow === true) => (shallow === false) // 則表示需深度展開 // 繼續遞歸展開 if (!shallow) // flatten 方法返回數組 // 將上面定義的 value 從新賦值 value = flatten(value, shallow, strict); // 遞歸展開到最後一層(沒有嵌套的數組了) // 或者 (shallow === true) => 只展開一層 // value 值確定是一個數組 var j = 0, len = value.length; // 這一步貌似沒有必要 // 畢竟 JavaScript 的數組會自動擴充 // 可是這樣寫,感受比較好,對於元素的 push 過程有個比較清晰的認識 output.length += len; // 將 value 數組的元素添加到 output 數組中 while (j < len) { output[idx++] = value[j++]; } } else if (!strict) { // (!strict === true) => (strict === false) // 若是是深度展開,即 shallow 參數爲 false // 那麼當最後 value 不是數組,是基本類型時 // 確定會走到這個 else-if 判斷中 // 而若是此時 strict 爲 true,則不能跳到這個分支內部 // 因此 shallow === false 若是和 strict === true 搭配 // 調用 flatten 方法獲得的結果永遠是空數組 [] output[idx++] = value; } } return output; }; // Flatten out an array, either recursively (by default), or just one level. // 將嵌套的數組展開 // 若是參數 (shallow === true),則僅展開一層 // _.flatten([1, [2], [3, [[4]]]]); // => [1, 2, 3, 4]; // ====== // // _.flatten([1, [2], [3, [[4]]]], true); // => [1, 2, 3, [[4]]]; _.flatten = function(array, shallow) { // array => 須要展開的數組 // shallow => 是否只展開一層 // false 爲 flatten 方法 strict 變量 return flatten(array, shallow, false); }; // Return a version of the array that does not contain the specified value(s). // without_.without(array, *values) // Returns a copy of the array with all instances of the values removed. // ====== // // _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4] // ===== // // 從數組中移除指定的元素 // 返回移除後的數組副本 _.without = function(array) { // slice.call(arguments, 1) // 將 arguments 轉爲數組(同時去掉第一個元素) // 以後即可以調用 _.difference 方法 return _.difference(array, slice.call(arguments, 1)); }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. // 數組去重 // 若是第二個參數 `isSorted` 爲 true // 則說明事先已經知道數組有序 // 程序會跑一個更快的算法(一次線性比較,元素和數組前一個元素比較便可) // 若是有第三個參數 iteratee,則對數組每一個元素迭代 // 對迭代以後的結果進行去重 // 返回去重後的數組(array 的子數組) // PS: 暴露的 API 中沒 context 參數 // _.uniq(array, [isSorted], [iteratee]) _.uniq = _.unique = function(array, isSorted, iteratee, context) { // 沒有傳入 isSorted 參數 // 轉爲 _.unique(array, false, undefined, iteratee) if (!_.isBoolean(isSorted)) { context = iteratee; iteratee = isSorted; isSorted = false; } // 若是有迭代函數 // 則根據 this 指向二次返回新的迭代函數 if (iteratee != null) iteratee = cb(iteratee, context); // 結果數組,是 array 的子集 var result = []; // 已經出現過的元素(或者通過迭代過的值) // 用來過濾重複值 var seen = []; for (var i = 0, length = getLength(array); i < length; i++) { var value = array[i], // 若是指定了迭代函數 // 則對數組每個元素進行迭代 // 迭代函數傳入的三個參數一般是 value, index, array 形式 computed = iteratee ? iteratee(value, i, array) : value; // 若是是有序數組,則當前元素只需跟上一個元素對比便可 // 用 seen 變量保存上一個元素 if (isSorted) { // 若是 i === 0,是第一個元素,則直接 push // 不然比較當前元素是否和前一個元素相等 if (!i || seen !== computed) result.push(value); // seen 保存當前元素,供下一次對比 seen = computed; } else if (iteratee) { // 若是 seen[] 中沒有 computed 這個元素值 if (!_.contains(seen, computed)) { seen.push(computed); result.push(value); } } else if (!_.contains(result, value)) { // 若是不用通過迭代函數計算,也就不用 seen[] 變量了 result.push(value); } } return result; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. // union_.union(*arrays) // Computes the union of the passed-in arrays: // the list of unique items, in order, that are present in one or more of the arrays. // ========== // // _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); // => [1, 2, 3, 101, 10] // ========== // // 將多個數組的元素集中到一個數組中 // 而且去重,返回數組副本 _.union = function() { // 首先用 flatten 方法將傳入的數組展開成一個數組 // 而後就能夠愉快地調用 _.uniq 方法了 // 假設 _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); // arguments 爲 [[1, 2, 3], [101, 2, 1, 10], [2, 1]] // shallow 參數爲 true,展開一層 // 結果爲 [1, 2, 3, 101, 2, 1, 10, 2, 1] // 而後對其去重 return _.uniq(flatten(arguments, true, true)); }; // Produce an array that contains every item shared between all the // passed-in arrays. // 尋找幾個數組中共有的元素 // 將這些每一個數組中都有的元素存入另外一個數組中返回 // _.intersection(*arrays) // _.intersection([1, 2, 3, 1], [101, 2, 1, 10, 1], [2, 1, 1]) // => [1, 2] // 注意:返回的結果數組是去重的 _.intersection = function(array) { // 結果數組 var result = []; // 傳入的參數(數組)個數 var argsLength = arguments.length; // 遍歷第一個數組的元素 for (var i = 0, length = getLength(array); i < length; i++) { var item = array[i]; // 若是 result[] 中已經有 item 元素了,continue // 即 array 中出現了相同的元素 // 返回的 result[] 實際上是個 "集合"(是去重的) if (_.contains(result, item)) continue; // 判斷其餘參數數組中是否都有 item 這個元素 for (var j = 1; j < argsLength; j++) { if (!_.contains(arguments[j], item)) break; } // 遍歷其餘參數數組完畢 // j === argsLength 說明其餘參數數組中都有 item 元素 // 則將其放入 result[] 中 if (j === argsLength) result.push(item); } return result; }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. // _.difference(array, *others) // Similar to without, but returns the values from array that are not present in the other arrays. // ===== // // _.difference([1, 2, 3, 4, 5], [5, 2, 10]); // => [1, 3, 4] // ===== // // 剔除 array 數組中在 others 數組中出現的元素 _.difference = function(array) { // 將 others 數組展開一層 // rest[] 保存展開後的元素組成的數組 // strict 參數爲 true // 不能夠這樣用 _.difference([1, 2, 3, 4, 5], [5, 2], 10); // 10 就會取不到 var rest = flatten(arguments, true, true, 1); // 遍歷 array,過濾 return _.filter(array, function(value){ // 若是 value 存在在 rest 中,則過濾掉 return !_.contains(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. // ===== // // _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); // => [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]] // ===== // // 將多個數組中相同位置的元素歸類 // 返回一個數組 _.zip = function() { return _.unzip(arguments); }; // Complement of _.zip. Unzip accepts an array of arrays and groups // each array's elements on shared indices // The opposite of zip. Given an array of arrays, // returns a series of new arrays, // the first of which contains all of the first elements in the input arrays, // the second of which contains all of the second elements, and so on. // ===== // // _.unzip([["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]); // => [['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]] // ===== // _.unzip = function(array) { var length = array && _.max(array, getLength).length || 0; var result = Array(length); for (var index = 0; index < length; index++) { result[index] = _.pluck(array, index); } return result; }; // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. // 將數組轉化爲對象 _.object = function(list, values) { var result = {}; for (var i = 0, length = getLength(list); i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // Generator function to create the findIndex and findLastIndex functions // (dir === 1) => 從前日後找 // (dir === -1) => 從後往前找 function createPredicateIndexFinder(dir) { // 經典閉包 return function(array, predicate, context) { predicate = cb(predicate, context); var length = getLength(array); // 根據 dir 變量來肯定數組遍歷的起始位置 var index = dir > 0 ? 0 : length - 1; for (; index >= 0 && index < length; index += dir) { // 找到第一個符合條件的元素 // 並返回下標值 if (predicate(array[index], index, array)) return index; } return -1; }; } // Returns the first index on an array-like that passes a predicate test // 從前日後找到數組中 `第一個知足條件` 的元素,並返回下標值 // 沒找到返回 -1 // _.findIndex(array, predicate, [context]) _.findIndex = createPredicateIndexFinder(1); // 從後往前找到數組中 `第一個知足條件` 的元素,並返回下標值 // 沒找到返回 -1 // _.findLastIndex(array, predicate, [context]) _.findLastIndex = createPredicateIndexFinder(-1); // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. // The iteratee may also be the string name of the property to sort by (eg. length). // ===== // // _.sortedIndex([10, 20, 30, 40, 50], 35); // => 3 // ===== // // var stooges = [{name: 'moe', age: 40}, {name: 'curly', age: 60}]; // _.sortedIndex(stooges, {name: 'larry', age: 50}, 'age'); // => 1 // ===== // // 二分查找 // 將一個元素插入已排序的數組 // 返回該插入的位置下標 // _.sortedIndex(list, value, [iteratee], [context]) _.sortedIndex = function(array, obj, iteratee, context) { // 注意 cb 方法 // iteratee 爲空 || 爲 String 類型(key 值)時會返回不一樣方法 iteratee = cb(iteratee, context, 1); // 通過迭代函數計算的值 // 可打印 iteratee 出來看看 var value = iteratee(obj); var low = 0, high = getLength(array); // 二分查找 while (low < high) { var mid = Math.floor((low + high) / 2); if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; } return low; }; // Generator function to create the indexOf and lastIndexOf functions // _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex); // _.lastIndexOf = createIndexFinder(-1, _.findLastIndex); function createIndexFinder(dir, predicateFind, sortedIndex) { // API 調用形式 // _.indexOf(array, value, [isSorted]) // _.indexOf(array, value, [fromIndex]) // _.lastIndexOf(array, value, [fromIndex]) return function(array, item, idx) { var i = 0, length = getLength(array); // 若是 idx 爲 Number 類型 // 則規定查找位置的起始點 // 那麼第三個參數不是 [isSorted] // 因此不能用二分查找優化了 // 只能遍歷查找 if (typeof idx == 'number') { if (dir > 0) { // 正向查找 // 重置查找的起始位置 i = idx >= 0 ? idx : Math.max(idx + length, i); } else { // 反向查找 // 若是是反向查找,重置 length 屬性值 length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; } } else if (sortedIndex && idx && length) { // 能用二分查找加速的條件 // 有序 & idx !== 0 && length !== 0 // 用 _.sortIndex 找到有序數組中 item 正好插入的位置 idx = sortedIndex(array, item); // 若是正好插入的位置的值和 item 恰好相等 // 說明該位置就是 item 第一次出現的位置 // 返回下標 // 不然便是沒找到,返回 -1 return array[idx] === item ? idx : -1; } // 特判,若是要查找的元素是 NaN 類型 // 若是 item !== item // 那麼 item => NaN if (item !== item) { idx = predicateFind(slice.call(array, i, length), _.isNaN); return idx >= 0 ? idx + i : -1; } // O(n) 遍歷數組 // 尋找和 item 相同的元素 // 特判排除了 item 爲 NaN 的狀況 // 能夠放心地用 `===` 來判斷是否相等了 for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { if (array[idx] === item) return idx; } return -1; }; } // Return the position of the first occurrence of an item in an array, // or -1 if the item is not included in the array. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. // _.indexOf(array, value, [isSorted]) // 找到數組 array 中 value 第一次出現的位置 // 並返回其下標值 // 若是數組有序,則第三個參數能夠傳入 true // 這樣算法效率會更高(二分查找) // [isSorted] 參數表示數組是否有序 // 同時第三個參數也能夠表示 [fromIndex] (見下面的 _.lastIndexOf) _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex); // 和 _indexOf 類似 // 反序查找 // _.lastIndexOf(array, value, [fromIndex]) // [fromIndex] 參數表示從倒數第幾個開始往前找 _.lastIndexOf = createIndexFinder(-1, _.findLastIndex); // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). // 返回某一個範圍內的數組成的數組 _.range = function(start, stop, step) { if (stop == null) { stop = start || 0; start = 0; } step = step || 1; // 返回數組的長度 var length = Math.max(Math.ceil((stop - start) / step), 0); // 返回的數組 var range = Array(length); for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; } return range; }; // Function (ahem) Functions // 函數的擴展方法 // 共 14 個擴展方法 // ------------------ // Determines whether to execute a function as a constructor // or a normal function with the provided arguments var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) { // 非 new 調用 _.bind 返回的方法(即 bound) // callingContext 不是 boundFunc 的一個實例 if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); // 若是是用 new 調用 _.bind 返回的方法 // self 爲 sourceFunc 的實例,繼承了它的原型鏈 // self 理論上是一個空對象(還沒賦值),可是有原型鏈 var self = baseCreate(sourceFunc.prototype); // 用 new 生成一個構造函數的實例 // 正常狀況下是沒有返回值的,即 result 值爲 undefined // 若是構造函數有返回值 // 若是返回值是對象(非 null),則 new 的結果返回這個對象 // 不然返回實例 // @see http://www.cnblogs.com/zichi/p/4392944.html var result = sourceFunc.apply(self, args); // 若是構造函數返回了對象 // 則 new 的結果是這個對象 // 返回這個對象 if (_.isObject(result)) return result; // 不然返回 self // var result = sourceFunc.apply(self, args); // self 對象當作參數傳入 // 會直接改變值 return self; }; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. // ES5 bind 方法的擴展(polyfill) // 將 func 中的 this 指向 context(對象) // _.bind(function, object, *arguments) // 可選的 arguments 參數會被看成 func 的參數傳入 // func 在調用時,會優先用 arguments 參數,而後使用 _.bind 返回方法所傳入的參數 _.bind = function(func, context) { // 若是瀏覽器支持 ES5 bind 方法,而且 func 上的 bind 方法沒有被重寫 // 則優先使用原生的 bind 方法 if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); // 若是傳入的參數 func 不是方法,則拋出錯誤 if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); // polyfill // 經典閉包,函數返回函數 // args 獲取優先使用的參數 var args = slice.call(arguments, 2); var bound = function() { // args.concat(slice.call(arguments)) // 最終函數的實際調用參數由兩部分組成 // 一部分是傳入 _.bind 的參數(會被優先調用) // 另外一部分是傳入 bound(_.bind 所返回方法)的參數 return executeBound(func, bound, context, this, args.concat(slice.call(arguments))); }; return bound; }; // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _ acts // as a placeholder, allowing any combination of arguments to be pre-filled. // _.partial(function, *arguments) // _.partial 能返回一個方法 // pre-fill 該方法的一些參數 _.partial = function(func) { // 提取但願 pre-fill 的參數 // 若是傳入的是 _,則這個位置的參數暫時空着,等待手動填入 var boundArgs = slice.call(arguments, 1); var bound = function() { var position = 0, length = boundArgs.length; var args = Array(length); for (var i = 0; i < length; i++) { // 若是該位置的參數爲 _,則用 bound 方法的參數填充這個位置 // args 爲調用 _.partial 方法的 pre-fill 的參數 & bound 方法的 arguments args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i]; } // bound 方法還有剩餘的 arguments,添上去 while (position < arguments.length) args.push(arguments[position++]); return executeBound(func, bound, this, this, args); }; return bound; }; // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. // 指定一系列方法(methodNames)中的 this 指向(object) // _.bindAll(object, *methodNames) _.bindAll = function(obj) { var i, length = arguments.length, key; // 若是隻傳入了一個參數(obj),沒有傳入 methodNames,則報錯 if (length <= 1) throw new Error('bindAll must be passed function names'); // 遍歷 methodNames for (i = 1; i < length; i++) { key = arguments[i]; // 逐個綁定 obj[key] = _.bind(obj[key], obj); } return obj; }; // Memoize an expensive function by storing its results. //「記憶化」,存儲中間運算結果,提升效率 // 參數 hasher 是個 function,用來計算 key // 若是傳入了 hasher,則用 hasher 來計算 key // 不然用 key 參數直接當 key(即 memoize 方法傳入的第一個參數) // _.memoize(function, [hashFunction]) // 適用於須要大量重複求值的場景 // 好比遞歸求解菲波那切數 // @http://www.jameskrob.com/memoize.html // create hash for storing "expensive" function outputs // run expensive function // check whether function has already been run with given arguments via hash lookup // if false - run function, and store output in hash // if true, return output stored in hash _.memoize = function(func, hasher) { var memoize = function(key) { // 儲存變量,方便使用 var cache = memoize.cache; // 求 key // 若是傳入了 hasher,則用 hasher 函數來計算 key // 不然用 參數 key(即 memoize 方法傳入的第一個參數)當 key var address = '' + (hasher ? hasher.apply(this, arguments) : key); // 若是這個 key 還沒被 hash 過(還沒求過值) if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); // 返回 return cache[address]; }; // cache 對象被當作 key-value 鍵值對緩存中間運算結果 memoize.cache = {}; // 返回一個函數(經典閉包) return memoize; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. // 延遲觸發某方法 // _.delay(function, wait, *arguments) // 若是傳入了 arguments 參數,則會被看成 func 的參數在觸發時調用 // 實際上是封裝了「延遲觸發某方法」,使其複用 _.delay = function(func, wait) { // 獲取 *arguments // 是 func 函數所須要的參數 var args = slice.call(arguments, 2); return setTimeout(function(){ // 將參數賦予 func 函數 return func.apply(null, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. // 和 setTimeout(func, 0) 類似(源碼看來彷佛應該是 setTimeout(func, 1)) // _.defer(function, *arguments) // 若是傳入 *arguments,會被當作參數,和 _.delay 調用方式相似(少了第二個參數) // 其實核心仍是調用了 _.delay 方法,但第二個參數(wait 參數)設置了默認值爲 1 // 如何使得方法能設置默認值?用 _.partial 方法 _.defer = _.partial(_.delay, _, 1); // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. // 函數節流(若是有連續事件響應,則每間隔必定時間段觸發) // 每間隔 wait(Number) milliseconds 觸發一次 func 方法 // 若是 options 參數傳入 {leading: false} // 那麼不會立刻觸發(等待 wait milliseconds 後第一次觸發 func) // 若是 options 參數傳入 {trailing: false} // 那麼最後一次回調不會被觸發 // **Notice: options 不能同時設置 leading 和 trailing 爲 false** // 示例: // var throttled = _.throttle(updatePosition, 100); // $(window).scroll(throttled); // 調用方式(注意看 A 和 B console.log 打印的位置): // _.throttle(function, wait, [options]) // sample 1: _.throttle(function(){}, 1000) // print: A, B, B, B ... // sample 2: _.throttle(function(){}, 1000, {leading: false}) // print: B, B, B, B ... // sample 3: _.throttle(function(){}, 1000, {trailing: false}) // print: A, A, A, A ... // ----------------------------------------- // _.throttle = function(func, wait, options) { var context, args, result; // setTimeout 的 handler var timeout = null; // 標記時間戳 // 上一次執行回調的時間戳 var previous = 0; // 若是沒有傳入 options 參數 // 則將 options 參數置爲空對象 if (!options) options = {}; var later = function() { // 若是 options.leading === false // 則每次觸發回調後將 previous 置爲 0 // 不然置爲當前時間戳 previous = options.leading === false ? 0 : _.now(); timeout = null; // console.log('B') result = func.apply(context, args); // 這裏的 timeout 變量必定是 null 了吧 // 是否沒有必要進行判斷? if (!timeout) context = args = null; }; // 以滾輪事件爲例(scroll) // 每次觸發滾輪事件即執行這個返回的方法 // _.throttle 方法返回的函數 return function() { // 記錄當前時間戳 var now = _.now(); // 第一次執行回調(此時 previous 爲 0,以後 previous 值爲上一次時間戳) // 而且若是程序設定第一個回調不是當即執行的(options.leading === false) // 則將 previous 值(表示上次執行的時間戳)設爲 now 的時間戳(第一次觸發時) // 表示剛執行過,此次就不用執行了 if (!previous && options.leading === false) previous = now; // 距離下次觸發 func 還須要等待的時間 var remaining = wait - (now - previous); context = this; args = arguments; // 要麼是到了間隔時間了,隨即觸發方法(remaining <= 0) // 要麼是沒有傳入 {leading: false},且第一次觸發回調,即當即觸發 // 此時 previous 爲 0,wait - (now - previous) 也知足 <= 0 // 以後便會把 previous 值迅速置爲 now // ========= // // remaining > wait,表示客戶端系統時間被調整過 // 則立刻執行 func 函數 // @see https://blog.coding.net/blog/the-difference-between-throttle-and-debounce-in-underscorejs // ========= // // console.log(remaining) 能夠打印出來看看 if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); // 解除引用,防止內存泄露 timeout = null; } // 重置前一次觸發的時間戳 previous = now; // 觸發方法 // result 爲該方法返回值 // console.log('A') result = func.apply(context, args); // 引用置爲空,防止內存泄露 // 感受這裏的 timeout 確定是 null 啊?這個 if 判斷不必吧? if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { // 最後一次須要觸發的狀況 // 若是已經存在一個定時器,則不會進入該 if 分支 // 若是 {trailing: false},即最後一次不須要觸發了,也不會進入這個分支 // 間隔 remaining milliseconds 後觸發 later 方法 timeout = setTimeout(later, remaining); } // 回調返回值 return result; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. // 函數去抖(連續事件觸發結束後只觸發一次) // sample 1: _.debounce(function(){}, 1000) // 連續事件結束後的 1000ms 後觸發 // sample 1: _.debounce(function(){}, 1000, true) // 連續事件觸發後當即觸發(此時會忽略第二個參數) _.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; var later = function() { // 定時器設置的回調 later 方法的觸發時間,和連續事件觸發的最後一次時間戳的間隔 // 若是間隔爲 wait(或者恰好大於 wait),則觸發事件 var last = _.now() - timestamp; // 時間間隔 last 在 [0, wait) 中 // 還沒到觸發的點,則繼續設置定時器 // last 值應該不會小於 0 吧? if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last); } else { // 到了能夠觸發的時間點 timeout = null; // 能夠觸發了 // 而且不是設置爲當即觸發的 // 由於若是是當即觸發(callNow),也會進入這個回調中 // 主要是爲了將 timeout 值置爲空,使之不影響下次連續事件的觸發 // 若是不是當即執行,隨即執行 func 方法 if (!immediate) { // 執行 func 函數 result = func.apply(context, args); // 這裏的 timeout 必定是 null 了吧 // 感受這個判斷多餘了 if (!timeout) context = args = null; } } }; // 嗯,閉包返回的函數,是能夠傳入參數的 // 也是 DOM 事件所觸發的回調函數 return function() { // 能夠指定 this 指向 context = this; args = arguments; // 每次觸發函數,更新時間戳 // later 方法中取 last 值時用到該變量 // 判斷距離上次觸發事件是否已通過了 wait seconds 了 // 即咱們須要距離最後一次事件觸發 wait seconds 後觸發這個回調方法 timestamp = _.now(); // 當即觸發須要知足兩個條件 // immediate 參數爲 true,而且 timeout 還沒設置 // immediate 參數爲 true 是顯而易見的 // 若是去掉 !timeout 的條件,就會一直觸發,而不是觸發一次 // 由於第一次觸發後已經設置了 timeout,因此根據 timeout 是否爲空能夠判斷是不是首次觸發 var callNow = immediate && !timeout; // 設置 wait seconds 後觸發 later 方法 // 不管是否 callNow(若是是 callNow,也進入 later 方法,去 later 方法中判斷是否執行相應回調函數) // 在某一段的連續觸發中,只會在第一次觸發時進入這個 if 分支中 if (!timeout) // 設置了 timeout,因此之後不會進入這個 if 分支了 timeout = setTimeout(later, wait); // 若是是當即觸發 if (callNow) { // func 多是有返回值的 result = func.apply(context, args); // 解除引用 context = args = null; } return result; }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return _.partial(wrapper, func); }; // Returns a negated version of the passed-in predicate. // 返回一個 predicate 方法的對立方法 // 即該方法能夠對原來的 predicate 迭代結果值取補集 _.negate = function(predicate) { return function() { return !predicate.apply(this, arguments); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. // _.compose(*functions) // var tmp = _.compose(f, g, h) // tmp(args) => f(g(h(args))) _.compose = function() { var args = arguments; // funcs var start = args.length - 1; // 倒序調用 return function() { var i = start; var result = args[start].apply(this, arguments); // 一個一個方法地執行 while (i--) result = args[i].call(this, result); return result; }; }; // Returns a function that will only be executed on and after the Nth call. // 第 times 觸發執行 func(事實上以後的每次觸發仍是會執行 func) // 有什麼用呢? // 若是有 N 個異步事件,全部異步執行完後執行該回調,即 func 方法(聯想 eventproxy) // _.after 會返回一個函數 // 當這個函數第 times 被執行的時候 // 觸發 func 方法 _.after = function(times, func) { return function() { // 函數被觸發了 times 了,則執行 func 函數 // 事實上 times 次後若是函數繼續被執行,也會觸發 func if (--times < 1) { return func.apply(this, arguments); } }; }; // Returns a function that will only be executed up to (but not including) the Nth call. // 函數至多被調用 times - 1 次((but not including) the Nth call) // func 函數會觸發 time - 1 次(Creates a version of the function that can be called no more than count times) // func 函數有個返回值,前 time - 1 次觸發的返回值都是將參數代入從新計算的 // 第 times 開始的返回值爲第 times - 1 次時的返回值(不從新計算) // The result of the last function call is memoized and returned when count has been reached. _.before = function(times, func) { var memo; return function() { if (--times > 0) { // 緩存函數執行結果 memo = func.apply(this, arguments); } // func 引用置爲空,其實不置爲空也用不到 func 了 if (times <= 1) func = null; // 前 times - 1 次觸發,memo 都是分別計算返回 // 第 times 次開始,memo 值同 times - 1 次時的 memo return memo; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. // 函數至多隻能被調用一次 // 適用於這樣的場景,某些函數只能被初始化一次,不得不設置一個變量 flag // 初始化後設置 flag 爲 true,以後不斷 check flag // ====== // // 實際上是調用了 _.before 方法,而且將 times 參數設置爲了默認值 2(也就是 func 至多能被調用 2 - 1 = 1 次) _.once = _.partial(_.before, 2); // Object Functions // 對象的擴展方法 // 共 38 個擴展方法 // ---------------- // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. // IE < 9 下 不能用 for key in ... 來枚舉對象的某些 key // 好比重寫了對象的 `toString` 方法,這個 key 值就不能在 IE < 9 下用 for in 枚舉到 // IE < 9,{toString: null}.propertyIsEnumerable('toString') 返回 false // IE < 9,重寫的 `toString` 屬性被認爲不可枚舉 // 據此能夠判斷是否在 IE < 9 瀏覽器環境中 var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); // IE < 9 下不能用 for in 來枚舉的 key 值集合 // 其實還有個 `constructor` 屬性 // 我的以爲多是 `constructor` 和其餘屬性不屬於一類 // nonEnumerableProps[] 中都是方法 // 而 constructor 表示的是對象的構造函數 // 因此區分開來了 var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; // obj 爲須要遍歷鍵值對的對象 // keys 爲鍵數組 // 利用 JavaScript 按值傳遞的特色 // 傳入數組做爲參數,能直接改變數組的值 function collectNonEnumProps(obj, keys) { var nonEnumIdx = nonEnumerableProps.length; var constructor = obj.constructor; // 獲取對象的原型 // 若是 obj 的 constructor 被重寫 // 則 proto 變量爲 Object.prototype // 若是沒有被重寫 // 則爲 obj.constructor.prototype var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto; // Constructor is a special case. // `constructor` 屬性須要特殊處理 (是否有必要?) // see https://github.com/hanzichi/underscore-analysis/issues/3 // 若是 obj 有 `constructor` 這個 key // 而且該 key 沒有在 keys 數組中 // 存入 keys 數組 var prop = 'constructor'; if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); // 遍歷 nonEnumerableProps 數組中的 keys while (nonEnumIdx--) { prop = nonEnumerableProps[nonEnumIdx]; // prop in obj 應該確定返回 true 吧?是否有判斷必要? // obj[prop] !== proto[prop] 判斷該 key 是否來自於原型鏈 // 便是否重寫了原型鏈上的屬性 if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) { keys.push(prop); } } } // Retrieve the names of an object's own properties. // Delegates to **ECMAScript 5**'s native `Object.keys` // ===== // // _.keys({one: 1, two: 2, three: 3}); // => ["one", "two", "three"] // ===== // // 返回一個對象的 keys 組成的數組 // 僅返回 own enumerable properties 組成的數組 _.keys = function(obj) { // 容錯 // 若是傳入的參數不是對象,則返回空數組 if (!_.isObject(obj)) return []; // 若是瀏覽器支持 ES5 Object.key() 方法 // 則優先使用該方法 if (nativeKeys) return nativeKeys(obj); var keys = []; // own enumerable properties for (var key in obj) // hasOwnProperty if (_.has(obj, key)) keys.push(key); // Ahem, IE < 9. // IE < 9 下不能用 for in 來枚舉某些 key 值 // 傳入 keys 數組爲參數 // 由於 JavaScript 下函數參數按值傳遞 // 因此 keys 當作參數傳入後會在 `collectNonEnumProps` 方法中改變值 if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; }; // Retrieve all the property names of an object. // 返回一個對象的 keys 數組 // 不只僅是 own enumerable properties // 還包括原型鏈上繼承的屬性 _.allKeys = function(obj) { // 容錯 // 不是對象,則返回空數組 if (!_.isObject(obj)) return []; var keys = []; for (var key in obj) keys.push(key); // Ahem, IE < 9. // IE < 9 下的 bug,同 _.keys 方法 if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; }; // Retrieve the values of an object's properties. // ===== // // _.values({one: 1, two: 2, three: 3}); // => [1, 2, 3] // ===== // // 將一個對象的全部 values 值放入數組中 // 僅限 own properties 上的 values // 不包括原型鏈上的 // 並返回該數組 _.values = function(obj) { // 僅包括 own properties var keys = _.keys(obj); var length = keys.length; var values = Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; }; // Returns the results of applying the iteratee to each element of the object // In contrast to _.map it returns an object // 跟 _.map 方法很像 // 可是是專門爲對象服務的 map 方法 // 迭代函數改變對象的 values 值 // 返回對象副本 _.mapObject = function(obj, iteratee, context) { // 迭代函數 // 對每一個鍵值對進行迭代 iteratee = cb(iteratee, context); var keys = _.keys(obj), length = keys.length, results = {}, // 對象副本,該方法返回的對象 currentKey; for (var index = 0; index < length; index++) { currentKey = keys[index]; // key 值不變 // 對每一個 value 值用迭代函數迭代 // 返回通過函數運算後的值 results[currentKey] = iteratee(obj[currentKey], currentKey, obj); } return results; }; // Convert an object into a list of `[key, value]` pairs. // 將一個對象轉換爲元素爲 [key, value] 形式的數組 // _.pairs({one: 1, two: 2, three: 3}); // => [["one", 1], ["two", 2], ["three", 3]] _.pairs = function(obj) { var keys = _.keys(obj); var length = keys.length; var pairs = Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; }; // Invert the keys and values of an object. The values must be serializable. // 將一個對象的 key-value 鍵值對顛倒 // 即原來的 key 爲 value 值,原來的 value 值爲 key 值 // 須要注意的是,value 值不能重複(否則後面的會覆蓋前面的) // 且新構造的對象符合對象構造規則 // 而且返回新構造的對象 _.invert = function(obj) { // 返回的新的對象 var result = {}; var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` // 傳入一個對象 // 遍歷該對象的鍵值對(包括 own properties 以及 原型鏈上的) // 若是某個 value 的類型是方法(function),則將該 key 存入數組 // 將該數組排序後返回 _.functions = _.methods = function(obj) { // 返回的數組 var names = []; // if IE < 9 // 且對象重寫了 `nonEnumerableProps` 數組中的某些方法 // 那麼這些方法名是不會被返回的 // 可見放棄了 IE < 9 可能對 `toString` 等方法的重寫支持 for (var key in obj) { // 若是某個 key 對應的 value 值類型是函數 // 則將這個 key 值存入數組 if (_.isFunction(obj[key])) names.push(key); } // 返回排序後的數組 return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). // extend_.extend(destination, *sources) // Copy all of the properties in the source objects over to the destination object // and return the destination object // It's in-order, so the last source will override properties of the same name in previous arguments. // 將幾個對象上(第二個參數開始,根據參數而定)的全部鍵值對添加到 destination 對象(第一個參數)上 // 由於 key 值可能會相同,因此後面的(鍵值對)可能會覆蓋前面的 // 參數個數 >= 1 _.extend = createAssigner(_.allKeys); // Assigns a given object with all the own properties in the passed-in object(s) // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) // 跟 extend 方法相似,可是隻把 own properties 拷貝給第一個參數對象 // 只繼承 own properties 的鍵值對 // 參數個數 >= 1 _.extendOwn = _.assign = createAssigner(_.keys); // Returns the first key on an object that passes a predicate test // 跟數組方法的 _.findIndex 相似 // 找到對象的鍵值對中第一個知足條件的鍵值對 // 並返回該鍵值對 key 值 _.findKey = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = _.keys(obj), key; // 遍歷鍵值對 for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; // 符合條件,直接返回 key 值 if (predicate(obj[key], key, obj)) return key; } }; // Return a copy of the object only containing the whitelisted properties. // 根據必定的需求(key 值,或者經過 predicate 函數返回真假) // 返回擁有必定鍵值對的對象副本 // 第二個參數能夠是一個 predicate 函數 // 也能夠是 >= 0 個 key // _.pick(object, *keys) // Return a copy of the object // filtered to only have values for the whitelisted keys (or array of valid keys) // Alternatively accepts a predicate indicating which keys to pick. /* _.pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age'); => {name: 'moe', age: 50} _.pick({name: 'moe', age: 50, userid: 'moe1'}, ['name', 'age']); => {name: 'moe', age: 50} _.pick({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) { return _.isNumber(value); }); => {age: 50} */ _.pick = function(object, oiteratee, context) { // result 爲返回的對象副本 var result = {}, obj = object, iteratee, keys; // 容錯 if (obj == null) return result; // 若是第二個參數是函數 if (_.isFunction(oiteratee)) { keys = _.allKeys(obj); iteratee = optimizeCb(oiteratee, context); } else { // 若是第二個參數不是函數 // 則後面的 keys 多是數組 // 也多是連續的幾個並列的參數 // 用 flatten 將它們展開 keys = flatten(arguments, false, false, 1); // 也轉爲 predicate 函數判斷形式 // 將指定 key 轉化爲 predicate 函數 iteratee = function(value, key, obj) { return key in obj; }; obj = Object(obj); } for (var i = 0, length = keys.length; i < length; i++) { var key = keys[i]; var value = obj[key]; // 知足條件 if (iteratee(value, key, obj)) result[key] = value; } return result; }; // Return a copy of the object without the blacklisted properties. // 跟 _.pick 方法相對 // 返回 _.pick 的補集 // 即返回沒有指定 keys 值的對象副本 // 或者返回不能經過 predicate 函數的對象副本 _.omit = function(obj, iteratee, context) { if (_.isFunction(iteratee)) { // _.negate 方法對 iteratee 的結果取反 iteratee = _.negate(iteratee); } else { var keys = _.map(flatten(arguments, false, false, 1), String); iteratee = function(value, key) { return !_.contains(keys, key); }; } return _.pick(obj, iteratee, context); }; // _.defaults(object, *defaults) // Fill in a given object with default properties. // Fill in undefined properties in object // with the first value present in the following list of defaults objects. // 和 _.extend 很是相似 // 區別是若是 *defaults 中出現了和 object 中同樣的鍵 // 則不覆蓋 object 的鍵值對 // 若是 *defaults 多個參數對象中有相同 key 的對象 // 則取最先出現的 value 值 // 參數個數 >= 1 _.defaults = createAssigner(_.allKeys, true); // Creates an object that inherits from the given prototype object. // If additional properties are provided then they will be added to the // created object. // 給定 prototype // 以及一些 own properties // 構造一個新的對象並返回 _.create = function(prototype, props) { var result = baseCreate(prototype); // 將 props 的鍵值對覆蓋 result 對象 if (props) _.extendOwn(result, props); return result; }; // Create a (shallow-cloned) duplicate of an object. // 對象的 `淺複製` 副本 // 注意點:全部嵌套的對象或者數組都會跟原對象用同一個引用 // 因此是爲淺複製,而不是深度克隆 _.clone = function(obj) { // 容錯,若是不是對象或者數組類型,則能夠直接返回 // 由於一些基礎類型是直接按值傳遞的 // 思考,arguments 呢? Nodelists 呢? HTML Collections 呢? if (!_.isObject(obj)) return obj; // 若是是數組,則用 obj.slice() 返回數組副本 // 若是是對象,則提取全部 obj 的鍵值對覆蓋空對象,返回 return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. // _.chain([1,2,3,200]) // .filter(function(num) { return num % 2 == 0; }) // .tap(alert) // .map(function(num) { return num * num }) // .value(); // => // [2, 200] (alerted) // => [4, 40000] // 主要是用在鏈式調用中 // 對中間值當即進行處理 _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Returns whether an object has a given set of `key:value` pairs. // attrs 參數爲一個對象 // 判斷 object 對象中是否有 attrs 中的全部 key-value 鍵值對 // 返回布爾值 _.isMatch = function(object, attrs) { // 提取 attrs 對象的全部 keys var keys = _.keys(attrs), length = keys.length; // 若是 object 爲空 // 根據 attrs 的鍵值對數量返回布爾值 if (object == null) return !length; // 這一步有必要? var obj = Object(object); // 遍歷 attrs 對象鍵值對 for (var i = 0; i < length; i++) { var key = keys[i]; // 若是 obj 對象沒有 attrs 對象的某個 key // 或者對於某個 key,它們的 value 值不一樣 // 則證實 object 並不擁有 attrs 的全部鍵值對 // 則返回 false if (attrs[key] !== obj[key] || !(key in obj)) return false; } return true; }; // Internal recursive comparison function for `isEqual`. // "內部的"/ "遞歸地"/ "比較" // 該內部方法會被遞歸調用 var eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). // a === b 時 // 須要注意 `0 === -0` 這個 special case // 0 和 -0 被認爲不相同(unequal) // 至於緣由能夠參考上面的連接 if (a === b) return a !== 0 || 1 / a === 1 / b; // A strict comparison is necessary because `null == undefined`. // 若是 a 和 b 有一個爲 null(或者 undefined) // 判斷 a === b if (a == null || b == null) return a === b; // Unwrap any wrapped objects. // 若是 a 和 b 是 underscore OOP 的對象 // 那麼比較 _wrapped 屬性值(Unwrap) if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. // 用 Object.prototype.toString.call 方法獲取 a 變量類型 var className = toString.call(a); // 若是 a 和 b 類型不相同,則返回 false // 類型都不一樣了還比較個蛋! if (className !== toString.call(b)) return false; switch (className) { // Strings, numbers, regular expressions, dates, and booleans are compared by value. // 以上五種類型的元素能夠直接根據其 value 值來比較是否相等 case '[object RegExp]': // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. // 轉爲 String 類型進行比較 return '' + a === '' + b; // RegExp 和 String 能夠看作一類 // 若是 obj 爲 RegExp 或者 String 類型 // 那麼 '' + obj 會將 obj 強制轉爲 String // 根據 '' + a === '' + b 便可判斷 a 和 b 是否相等 // ================ case '[object Number]': // `NaN`s are equivalent, but non-reflexive. // Object(NaN) is equivalent to NaN // 若是 +a !== +a // 那麼 a 就是 NaN // 判斷 b 是否也是 NaN 便可 if (+a !== +a) return +b !== +b; // An `egal` comparison is performed for other numeric values. // 排除了 NaN 干擾 // 還要考慮 0 的干擾 // 用 +a 將 Number() 形式轉爲基本類型 // 即 +Number(1) ==> 1 // 0 須要特判 // 若是 a 爲 0,判斷 1 / +a === 1 / b // 不然判斷 +a === +b return +a === 0 ? 1 / +a === 1 / b : +a === +b; // 若是 a 爲 Number 類型 // 要注意 NaN 這個 special number // NaN 和 NaN 被認爲 equal // ================ case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a === +b; // Date 和 Boolean 能夠看作一類 // 若是 obj 爲 Date 或者 Boolean // 那麼 +obj 會將 obj 轉爲 Number 類型 // 而後比較便可 // +new Date() 是當前時間距離 1970 年 1 月 1 日 0 點的毫秒數 // +true => 1 // +new Boolean(false) => 0 } // 判斷 a 是不是數組 var areArrays = className === '[object Array]'; // 若是 a 不是數組類型 if (!areArrays) { // 若是 a 不是 object 或者 b 不是 object // 則返回 false if (typeof a != 'object' || typeof b != 'object') return false; // 經過上個步驟的 if 過濾 // !!保證到此的 a 和 b 均爲對象!! // Objects with different constructors are not equivalent, but `Object`s or `Array`s // from different frames are. // 經過構造函數來判斷 a 和 b 是否相同 // 可是,若是 a 和 b 的構造函數不一樣 // 也並不必定 a 和 b 就是 unequal // 好比 a 和 b 在不一樣的 iframes 中! // aCtor instanceof aCtor 這步有點不大理解,啥用? var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor && _.isFunction(bCtor) && bCtor instanceof bCtor) && ('constructor' in a && 'constructor' in b)) { return false; } } // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. // Initializing stack of traversed objects. // It's done here since we only need them for objects and arrays comparison. // 第一次調用 eq() 函數,沒有傳入 aStack 和 bStack 參數 // 以後遞歸調用都會傳入這兩個參數 aStack = aStack || []; bStack = bStack || []; var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] === a) return bStack[length] === b; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); // Recursively compare objects and arrays. // 將嵌套的對象和數組展開 // 若是 a 是數組 // 由於嵌套,因此須要展開深度比較 if (areArrays) { // Compare array lengths to determine if a deep comparison is necessary. // 根據 length 判斷是否應該繼續遞歸對比 length = a.length; // 若是 a 和 b length 屬性大小不一樣 // 那麼顯然 a 和 b 不一樣 // return false 不用繼續比較了 if (length !== b.length) return false; // Deep compare the contents, ignoring non-numeric properties. while (length--) { // 遞歸 if (!eq(a[length], b[length], aStack, bStack)) return false; } } else { // 若是 a 不是數組 // 進入這個判斷分支 // Deep compare objects. // 兩個對象的深度比較 var keys = _.keys(a), key; length = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. // a 和 b 對象的鍵數量不一樣 // 那還比較毛? if (_.keys(b).length !== length) return false; while (length--) { // Deep compare each member // 遞歸比較 key = keys[length]; if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; } } // Remove the first object from the stack of traversed objects. // 與 aStack.push(a) 對應 // 此時 aStack 棧頂元素正是 a // 而代碼走到此步 // a 和 b isEqual 確認 // 因此 a,b 兩個元素能夠出棧 aStack.pop(); bStack.pop(); // 深度搜索遞歸比較完畢 // 放心地 return true return true; }; // Perform a deep comparison to check if two objects are equal. // 判斷兩個對象是否同樣 // new Boolean(true),true 被認爲 equal // [1, 2, 3], [1, 2, 3] 被認爲 equal // 0 和 -0 被認爲 unequal // NaN 和 NaN 被認爲 equal _.isEqual = function(a, b) { return eq(a, b); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. // 是不是 {}、[] 或者 "" 或者 null、undefined _.isEmpty = function(obj) { if (obj == null) return true; // 若是是數組、類數組、或者字符串 // 根據 length 屬性判斷是否爲空 // 後面的條件是爲了過濾 isArrayLike 對於 {length: 10} 這樣對象的判斷 bug? if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0; // 若是是對象 // 根據 keys 數量判斷是否爲 Empty return _.keys(obj).length === 0; }; // Is a given value a DOM element? // 判斷是否爲 DOM 元素 _.isElement = function(obj) { // 確保 obj 不是 null, undefined 等假值 // 而且 obj.nodeType === 1 return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray // 判斷是否爲數組 _.isArray = nativeIsArray || function(obj) { return toString.call(obj) === '[object Array]'; }; // Is a given variable an object? // 判斷是否爲對象 // 這裏的對象包括 function 和 object _.isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError. // 其餘類型判斷 _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) === '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE < 9), where // there isn't any inspectable "Arguments" type. // _.isArguments 方法在 IE < 9 下的兼容 // IE < 9 下對 arguments 調用 Object.prototype.toString.call 方法 // 結果是 => [object Object] // 而並不是咱們指望的 [object Arguments]。 // so 用是否含有 callee 屬性來作兼容 if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return _.has(obj, 'callee'); }; } // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8, // IE 11 (#1621), and in Safari 8 (#1929). // _.isFunction 在 old v8, IE 11 和 Safari 8 下的兼容 // 以爲這裏有點問題 // 我用的 chrome 49 (顯然不是 old v8) // 卻也進入了這個 if 判斷內部 if (typeof /./ != 'function' && typeof Int8Array != 'object') { _.isFunction = function(obj) { return typeof obj == 'function' || false; }; } // Is a given object a finite number? // 判斷是不是有限的數字 _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? (NaN is the only number which does not equal itself). // 判斷是不是 NaN // NaN 是惟一的一個 `本身不等於本身` 的 number 類型 // 這樣寫有 BUG // _.isNaN(new Number(0)) => true // 詳見 https://github.com/hanzichi/underscore-analysis/issues/13 // 最新版本(edge 版)已經修復該 BUG _.isNaN = function(obj) { return _.isNumber(obj) && obj !== +obj; }; // Is a given value a boolean? // 判斷是不是布爾值 // 基礎類型(true、 false) // 以及 new Boolean() 兩個方向判斷 // 有點多餘了吧? // 我的以爲直接用 toString.call(obj) 來判斷就能夠了 _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; }; // Is a given value equal to null? // 判斷是不是 null _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? // 判斷是不是 undefined // undefined 能被改寫 (IE < 9) // undefined 只是全局對象的一個屬性 // 在局部環境能被從新定義 // 可是「void 0」始終是 undefined _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). // 判斷對象中是否有指定 key // own properties, not on a prototype _.has = function(obj, key) { // obj 不能爲 null 或者 undefined return obj != null && hasOwnProperty.call(obj, key); }; // Utility Functions // 工具類方法 // 共 14 個擴展方法 // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. // 若是全局環境中已經使用了 `_` 變量 // 能夠用該方法返回其餘變量 // 繼續使用 underscore 中的方法 // var underscore = _.noConflict(); // underscore.each(..); _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iteratees. // 返回傳入的參數,看起來好像沒什麼卵用 // 其實 _.identity 在 undescore 內大量做爲迭代函數出現 // 能簡化不少迭代函數的書寫 _.identity = function(value) { return value; }; // Predicate-generating functions. Often useful outside of Underscore. _.constant = function(value) { return function() { return value; }; }; _.noop = function(){}; // 傳送門 /* var property = function(key) { return function(obj) { return obj == null ? void 0 : obj[key]; }; }; */ _.property = property; // Generates a function for a given object that returns a given property. _.propertyOf = function(obj) { return obj == null ? function(){} : function(key) { return obj[key]; }; }; // Returns a predicate for checking whether an object has a given set of // `key:value` pairs. // 判斷一個給定的對象是否有某些鍵值對 _.matcher = _.matches = function(attrs) { attrs = _.extendOwn({}, attrs); return function(obj) { return _.isMatch(obj, attrs); }; }; // Run a function **n** times. // 執行某函數 n 次 _.times = function(n, iteratee, context) { var accum = Array(Math.max(0, n)); iteratee = optimizeCb(iteratee, context, 1); for (var i = 0; i < n; i++) accum[i] = iteratee(i); return accum; }; // Return a random integer between min and max (inclusive). // 返回一個 [min, max] 範圍內的任意整數 _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; // A (possibly faster) way to get the current timestamp as an integer. // 返回當前時間的 "時間戳"(單位 ms) // 其實並非時間戳,時間戳還要除以 1000(單位 s) // +new Date 相似 _.now = Date.now || function() { return new Date().getTime(); }; // List of HTML entities for escaping. // HTML 實體編碼 // escapeMap 用於編碼 // see @http://www.cnblogs.com/zichi/p/5135636.html // in PHP, htmlspecialchars — Convert special characters to HTML entities // see @http://php.net/manual/zh/function.htmlspecialchars.php // 能將 & " ' < > 轉爲實體編碼(下面的前 5 種) var escapeMap = { '&': '&', '<': '<', '>': '>', '"': '"', // 以上四個爲最經常使用的字符實體 // 也是僅有的能夠在全部環境下使用的實體字符(其餘應該用「實體數字」,以下) // 瀏覽器也許並不支持全部實體名稱(對實體數字的支持卻很好) "'": ''', '`': '`' }; // _.invert 方法將一個對象的鍵值對對調 // unescapeMap 用於解碼 var unescapeMap = _.invert(escapeMap); // Functions for escaping and unescaping strings to/from HTML interpolation. var createEscaper = function(map) { var escaper = function(match) { return map[match]; }; // Regexes for identifying a key that needs to be escaped // 正則替換 // 注意下 ?: var source = '(?:' + _.keys(map).join('|') + ')'; // 正則 pattern var testRegexp = RegExp(source); // 全局替換 var replaceRegexp = RegExp(source, 'g'); return function(string) { string = string == null ? '' : '' + string; return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; }; }; // Escapes a string for insertion into HTML, replacing &, <, >, ", `, and ' characters. // 編碼,防止被 XSS 攻擊等一些安全隱患 _.escape = createEscaper(escapeMap); // The opposite of escape // replaces &, <, >, ", ` and ' with their unescaped counterparts // 解碼 _.unescape = createEscaper(unescapeMap); // If the value of the named `property` is a function then invoke it with the // `object` as context; otherwise, return it. _.result = function(object, property, fallback) { var value = object == null ? void 0 : object[property]; if (value === void 0) { value = fallback; } return _.isFunction(value) ? value.call(object) : value; }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. // 生成客戶端臨時的 DOM ids var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. // ERB => Embedded Ruby // Underscore 默認採用 ERB-style 風格模板,也能夠根據本身習慣自定義模板 // 1. <% %> - to execute some code // 2. <%= %> - to print some value in template // 3. <%- %> - to print some values HTML escaped _.templateSettings = { // 三種渲染模板 evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', // 回車符 '\n': 'n', // 換行符 // http://stackoverflow.com/questions/16686687/json-stringify-and-u2028-u2029-check '\u2028': 'u2028', // Line separator '\u2029': 'u2029' // Paragraph separator }; // RegExp pattern var escaper = /\\|'|\r|\n|\u2028|\u2029/g; var escapeChar = function(match) { /** ' => \\' \\ => \\\\ \r => \\r \n => \\n \u2028 => \\u2028 \u2029 => \\u2029 **/ return '\\' + escapes[match]; }; // 將 JavaScript 模板編譯爲能夠用於頁面呈現的函數 // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. // NB: `oldSettings` only exists for backwards compatibility. // oldSettings 參數爲了兼容 underscore 舊版本 // setting 參數能夠用來自定義字符串模板(可是 key 要和 _.templateSettings 中的相同,才能 overridden) // 1. <% %> - to execute some code // 2. <%= %> - to print some value in template // 3. <%- %> - to print some values HTML escaped // Compiles JavaScript templates into functions // _.template(templateString, [settings]) _.template = function(text, settings, oldSettings) { // 兼容舊版本 if (!settings && oldSettings) settings = oldSettings; // 相同的 key,優先選擇 settings 對象中的 // 其次選擇 _.templateSettings 對象中的 // 生成最終用來作模板渲染的字符串 // 自定義模板優先於默認模板 _.templateSettings // 若是定義了相同的 key,則前者會覆蓋後者 settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. // 正則表達式 pattern,用於正則匹配 text 字符串中的模板字符串 // /<%-([\s\S]+?)%>|<%=([\s\S]+?)%>|<%([\s\S]+?)%>|$/g // 注意最後還有個 |$ var matcher = RegExp([ // 注意下 pattern 的 source 屬性 (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. // 編譯模板字符串,將原始的模板字符串替換成函數字符串 // 用拼接成的函數字符串生成函數(new Function(...)) var index = 0; // source 變量拼接的字符串用來生成函數 // 用於當作 new Function 生成函數時的函數字符串變量 // 記錄編譯成的函數字符串,可經過 _.template(tpl).source 獲取(_.template(tpl) 返回方法) var source = "__p+='"; // replace 函數不須要爲返回值賦值,主要是爲了在函數內對 source 變量賦值 // 將 text 變量中的模板提取出來 // match 爲匹配的整個串 // escape/interpolate/evaluate 爲匹配的子表達式(若是沒有匹配成功則爲 undefined) // offset 爲字符匹配(match)的起始位置(偏移量) text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { // \n => \\n source += text.slice(index, offset).replace(escaper, escapeChar); // 改變 index 值,爲了下次的 slice index = offset + match.length; if (escape) { // 須要對變量進行編碼(=> HTML 實體編碼) // 避免 XSS 攻擊 source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } else if (interpolate) { // 單純的插入變量 source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } else if (evaluate) { // 能夠直接執行的 JavaScript 語句 // 注意 "__p+=",__p 爲渲染返回的字符串 source += "';\n" + evaluate + "\n__p+='"; } // Adobe VMs need the match returned to produce the correct offset. // return 的做用是? // 將匹配到的內容原樣返回(Adobe VMs 須要返回 match 來使得 offset 值正常) return match; }); source += "';\n"; // By default, `template` places the values from your data in the local scope via the `with` statement. // However, you can specify a single variable name with the variable setting. // This can significantly improve the speed at which a template is able to render. // If a variable is not specified, place data values in local scope. // 指定 scope // 若是設置了 settings.variable,能顯著提高模板的渲染速度 // 不然,默認用 with 語句指定做用域 if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; // 增長 print 功能 // __p 爲返回的字符串 source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n'; try { // render 方法,前兩個參數爲 render 方法的參數 // obj 爲傳入的 JSON 對象,傳入 _ 參數使得函數內部能用 Underscore 的函數 var render = new Function(settings.variable || 'obj', '_', source); } catch (e) { // 拋出錯誤 e.source = source; throw e; } // 返回的函數 // data 通常是 JSON 數據,用來渲染模板 var template = function(data) { // render 爲模板渲染函數 // 傳入參數 _ ,使得模板裏 <% %> 裏的代碼能用 underscore 的方法 //(<% %> - to execute some code) return render.call(this, data, _); }; // Provide the compiled source as a convenience for precompilation. // template.source for debug? // obj 與 with(obj||{}) 中的 obj 對應 var argument = settings.variable || 'obj'; // 可經過 _.template(tpl).source 獲取 // 能夠用來預編譯,在服務端預編譯好,直接在客戶端生成代碼,客戶端直接調用方法 // 這樣若是出錯就能打印出錯行 // Precompiling your templates can be a big help when debugging errors you can't reproduce. // This is because precompiled templates can provide line numbers and a stack trace, // something that is not possible when compiling templates on the client. // The source property is available on the compiled template function for easy precompilation. // see @http://stackoverflow.com/questions/18755292/underscore-js-precompiled-templates-using // see @http://stackoverflow.com/questions/13536262/what-is-javascript-template-precompiling // see @http://stackoverflow.com/questions/40126223/can-anyone-explain-underscores-precompilation-in-template // JST is a server-side thing, not client-side. // This mean that you compile Unserscore template on server side by some server-side script and save the result in a file. // Then use this file as compiled Unserscore template. template.source = 'function(' + argument + '){\n' + source + '}'; return template; }; // Add a "chain" function. Start chaining a wrapped Underscore object. // 使支持鏈式調用 /** // 非 OOP 調用 chain _.chain([1, 2, 3]) .map(function(a) { return a * 2; }) .reverse().value(); // [6, 4, 2] // OOP 調用 chain _([1, 2, 3]) .chain() .map(function(a){ return a * 2; }) .first() .value(); // 2 **/ _.chain = function(obj) { // 不管是否 OOP 調用,都會轉爲 OOP 形式 // 而且給新的構造對象添加了一個 _chain 屬性 var instance = _(obj); // 標記是否使用鏈式操做 instance._chain = true; // 返回 OOP 對象 // 能夠看到該 instance 對象除了多了個 _chain 屬性 // 其餘的和直接 _(obj) 的結果同樣 return instance; }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // OOP // 若是 `_` 被當作方法(構造函數)調用, 則返回一個被包裝過的對象 // 該對象能使用 underscore 的全部方法 // 而且支持鏈式調用 // Helper function to continue chaining intermediate results. // 一個幫助方法(Helper function) var result = function(instance, obj) { // 若是須要鏈式操做,則對 obj 運行 _.chain 方法,使得能夠繼續後續的鏈式操做 // 若是不須要,直接返回 obj return instance._chain ? _(obj).chain() : obj; }; // Add your own custom functions to the Underscore object. // 可向 underscore 函數庫擴展本身的方法 // obj 參數必須是一個對象(JavaScript 中一切皆對象) // 且本身的方法定義在 obj 的屬性上 // 如 obj.myFunc = function() {...} // 形如 {myFunc: function(){}} // 以後即可使用以下: _.myFunc(..) 或者 OOP _(..).myFunc(..) _.mixin = function(obj) { // 遍歷 obj 的 key,將方法掛載到 Underscore 上 // 實際上是將方法淺拷貝到 _.prototype 上 _.each(_.functions(obj), function(name) { // 直接把方法掛載到 _[name] 上 // 調用相似 _.myFunc([1, 2, 3], ..) var func = _[name] = obj[name]; // 淺拷貝 // 將 name 方法掛載到 _ 對象的原型鏈上,使之能 OOP 調用 _.prototype[name] = function() { // 第一個參數 var args = [this._wrapped]; // arguments 爲 name 方法須要的其餘參數 push.apply(args, arguments); // 執行 func 方法 // 支持鏈式操做 return result(this, func.apply(_, args)); }; }); }; // Add all of the Underscore functions to the wrapper object. // 將前面定義的 underscore 方法添加給包裝過的對象 // 即添加到 _.prototype 中 // 使 underscore 支持面向對象形式的調用 _.mixin(_); // Add all mutator Array functions to the wrapper. // 將 Array 原型鏈上有的方法都添加到 underscore 中 _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; // 支持鏈式操做 return result(this, obj); }; }); // Add all accessor Array functions to the wrapper. // 添加 concat、join、slice 等數組原生方法給 Underscore _.each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return result(this, method.apply(this._wrapped, arguments)); }; }); // Extracts the result from a wrapped and chained object. // 一個包裝過(OOP)而且鏈式調用的對象 // 用 value 方法獲取結果 // _(obj).value === obj? _.prototype.value = function() { return this._wrapped; }; // Provide unwrapping proxy for some methods used in engine operations // such as arithmetic and JSON stringification. _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; _.prototype.toString = function() { return '' + this._wrapped; }; // AMD registration happens at the end for compatibility with AMD loaders // that may not enforce next-turn semantics on modules. Even though general // practice for AMD registration is to be anonymous, underscore registers // as a named module because, like jQuery, it is a base library that is // popular enough to be bundled in a third party lib, but not be part of // an AMD load request. Those cases could generate an error when an // anonymous define() is called outside of a loader request. // 兼容 AMD 規範 if (typeof define === 'function' && define.amd) { define('underscore', [], function() { return _; }); } }.call(this));