Underscore.js 源碼學(xué)習(xí)

簡介

underscore.js作為一個優(yōu)秀的JavaScript工具庫,提供了很多使用的功能,同時考慮了瀏覽器的兼容性,并且代碼加上注釋只有2K行,很利于閱讀和學(xué)習(xí)。
使用版本:
_.VERSION = '1.8.3';

1 基礎(chǔ)

1.1 立即執(zhí)行函數(shù)

(function() {
  ...
}());

underscore.js的文件整體用一個立即執(zhí)行函數(shù)包裹,防止其內(nèi)部和其他代碼之間的相互污染。

1.2 獲取全局命名空間

1.3 使用變量保存常用函數(shù)

  var push = ArrayProto.push,
      slice = ArrayProto.slice,
      toString = ObjProto.toString,
      hasOwnProperty = ObjProto.hasOwnProperty;

因為在進行壓縮代碼的時候,push,slice等可以被替換為a,b等,而ArrayProto.push無法壓縮。

1.4 兼容Object.create

var Ctor = function() {}
var baseCreate = function(prototype) {
  if (!_.isObject(prototype)) return {};
  if (nativeCreate) return nativeCreate(prototype);
  Ctor.prototype = prototype;
  var result = new Ctor;
  Ctor.prototype = null;
  return result;
};

如果當(dāng)前環(huán)境不存在Object.create(),則用baseCreate代替。
因為Object.create(obj)是創(chuàng)建一個空的對象,使它的__porto__指向obj,所以要用一個暫時的類Ctor來實現(xiàn)。

1.5 回調(diào)函數(shù)封裝

2 函數(shù)處理相關(guān)

2.1 debounce

_.debounce(function, wait, [immediate])
function最后一次調(diào)用后,再等待wait時間后,再執(zhí)行最后一次函數(shù)。
如果immediatetrue,會在調(diào)用_.debounce(function, wait, [immediate])時,立即執(zhí)行一次,并且wait時間內(nèi)不會再執(zhí)行。
原理:
每次調(diào)用函數(shù)時,先clearTimeout(timeout),清除wait時間內(nèi)上次的函數(shù)調(diào)用
再執(zhí)行timeout(func,wait)
如果immediate為true,會馬上執(zhí)行一次,并且用一個空的func占位,timeout(func,wait)函數(shù),保證wait時間內(nèi)不會執(zhí)行第二次。

3. 判斷變量類型相關(guān)

3.1 isArray

如果存在es5以上支持的Array.isArray則用Array.isArray,否則通過調(diào)用Object.prototype.toString.call(array)來實現(xiàn)

var isArray = Array.isArray || function (obj) {
  return Object.prototype.toString.call(array) === '[object Array]'
}

3.2 isFunction

最好用的方法是type of obj == 'function' || false,注意IE8因為有bug,
type of obj == 'function' obj為object的時候,也會判斷為true,所以用這種方式修復(fù)了bug。

var nodelist = root.document && root.document.childNodes;
if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') {
  _.isFunction = function (obj) {
      return typeof obj == 'function' || false;
  };
}

3.3 isObject

obj為函數(shù)/對象的時候,都是object,此外因為type of null = 'object',所以去除了為null`的情況。

_.isObject = function (obj) {
  var type = typeof obj
  return type === 'function' || type === 'object' && !!object
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容