標籤:
underscore就是一些函數的集合,大概分為6部分,分別是基礎函數,集合,數組,函數,對象,實用功能.
在實現每一個功能的時候,基本上先自己實現,再對比。
(function(){
}.call(this));
基本架構長這樣,就一個函數的自調用,用window作為調用對象,防止汙染全域。
//把window對象先存起來備用吧。
var root = this;
//弄個window的屬性_;
var previousUnderscore = root._;
//存一些原型
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
//存一些原型的方法
var
push = ArrayProto.push,
slice = ArrayProto.slice,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
var
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind,
nativeCreate = Object.create;
//弄個備用的建構函式
var Ctor = function(){};
//建構函式_,obj是_執行個體的話,直接返回obj.若是直接調用建構函式而不是通過new操作符的話,會調用第二個if.執行new _(obj).
//另外,這樣的話obj就不是執行個體了,所以弄個執行個體屬性_wrapped把obj存起來備用。
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
//這個是什麼nodejs介面的,不懂。過了,嘿嘿
if (typeof exports !== ‘undefined‘) { if (typeof module !== ‘undefined‘ && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; }
//這個是關於函數最佳化的,參數函數,調用EC,參數數量。
//只傳了一個參數的話,context==null.這裡應該是可以用context === void 0或者context==null,一個意思。直接返回傳入的函數
//沒傳第三個參數的話,預設就是傳三個參數給調用的函數,一般是用在forEach,filter這些數組方法,function(element,index,array);
//第三個參數是1或2的話,感覺沒什麼特別的,直接調用吧.是4的話就是reduce函數之類的。
var optimizeCb = function(func, context, argCount) {
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);
};
case 3: return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
};
//沒傳參數的話,直接返回一個函數,設定a,調用這個函數a,返回傳給a的參數
//value是函數的話,直接調用上面的函數最佳化公式,
//對象的話,返回
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);
};
_.identity = function(value) {
return value;
};
underscore源碼解析