underscore中_是弄啥的
_在underscore中是以函數(shù)形式定義的對(duì)象,看看它的定義:
var _ = function(obj) {
// 如果參數(shù)是"_"的實(shí)例,直接返回,相當(dāng)于容錯(cuò)機(jī)制
if (obj instanceof _) return obj;
// 否則返回實(shí)例new _(obj), 繼續(xù)調(diào)用該函數(shù),下一次進(jìn)來之后直接保存下一步的變量_wrapped
if (!(this instanceof _)) return new _(obj);
// 實(shí)例對(duì)象_wrapped屬性中存儲(chǔ)了接受的參數(shù)
this._wrapped = obj;
};
① _是一個(gè)函數(shù),支持OOP調(diào)用的構(gòu)造函數(shù)
② underscore中的屬性和方法默認(rèn)都掛載在_下面:比如 _.each、_.map...等
實(shí)例:
// 直接調(diào)用
_.each([1, 2, 3], function(value, index){
console.log(value); // 1, 2, 3
});
// OOP方式調(diào)用
_([1, 2, 3]).each(function(value, index){
console.log(value); // 1, 2, 3
});
解析:
第一種直接調(diào)用就直接調(diào)用_.each()方法即可,因?yàn)榉椒J(rèn)都是掛載在_上面。
第二種就厲害了,第一個(gè)判斷是否是_實(shí)例,如果是直接返回該對(duì)象,_.chain方法就用到了該判斷。
第二個(gè)判斷this如果不是_實(shí)例,生成_對(duì)象實(shí)例并返回,繼而繼續(xù)從頭執(zhí)行該函數(shù),前兩個(gè)條件都不滿足,執(zhí)行最后一個(gè),把傳入的對(duì)象賦值給該實(shí)例_wrapped屬性,完成操作。
梳理一下:_在underscore中就是定義的一個(gè)函數(shù),可以作為OOP中構(gòu)造函數(shù)使用,然后把傳入的對(duì)象添加到生成的實(shí)例對(duì)象的_wrapped屬性中