2016-12-28 74 views
7

什麼是「權威」方式來檢測_變量是否裝有lodash或下劃線?檢測_是否爲下劃線或下劃線

我正在使用lodash在一個環境中的項目,其中underscore有時可能還會加載

目前,我已經想出了這一點:

/** 
* lodash defines a variable PLACEHOLDER = '__lodash_placeholder__' 
* so check if that is defined/contains the string "lodash" 
*/ 
if (typeof(_.PLACEHOLDER) == 'undefined' || _.PLACEHOLDER.indexOf('lodash') < 0) { 
    // _ is underscore, do what I need to access lodash 
} 

重要更新:上面的代碼不工作!

是否有一個「權威」的方式來檢測,如果_是lodash或下劃線?

注:
這是找到一種方法來確定是否lodash或下劃線裝入_可變提出具體要求:
1.這是我無法控制的下劃線是否加載與否。 (lodash 在我的控制範圍內,並且會一直加載)。
2.不能依賴lodash /下劃線的加載順序。
3.加載的下劃線的版本可能會發生變化(它是可以更新的CMS框架的一部分)。
4. Lodash 4.17.x有300多個功能。我的代碼利用lodash中的函數很多
5. Lodash包含許多功能,下劃線不提供提供。
6.兩個庫中存在的一些函數具有不同的實現。

+0

我能想到的唯一的事情就是'_ .VERSION'出現在'lodash'中,但不出現在'underscore' – bhantol

+2

@bhantol:下劃線也有'VERSION'(至少在其網站上的版本)。 –

+1

'isLodash = _.toString()。indexOf('lodash')> = 0' – bhantol

回答

1

發佈在問題中的代碼不起作用,因爲PLACEHOLDER是在縮小期間被重命名的私有變量。

因此,我修改了評論中提到的「特徵檢測」的概念。注意,此方法可能會打破,如果在所有的這些功能下劃線卷的未來版本,或者如果lodash不贊成任何一個功能:

var isLodash = false; 
 
// If _ is defined and the function _.forEach exists then we know underscore OR lodash are in place 
 
if ('undefined' != typeof(_) && 'function' == typeof(_.forEach)) { 
 
    // A small sample of some of the functions that exist in lodash but not underscore 
 
    var funcs = [ 'get', 'set', 'at', 'cloneDeep' ]; 
 
    // Simplest if assume exists to start 
 
    isLodash = true; 
 
    funcs.forEach(function (func) { 
 
    // If just one of the functions do not exist, then not lodash 
 
    isLodash = ('function' != typeof(_[ func ])) ? false : isLodash; 
 
    }); 
 
} 
 

 
if (isLodash) { 
 
    // We know that lodash is loaded in the _ variable 
 
    console.log('Is lodash: ' + isLodash); 
 
} else { 
 
    // We know that lodash is NOT loaded 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.3/lodash.js"></script>

3

一起爲@bhantol已經注意到類似的路線走,有一個Migrating doc與人與相容的lodash和下劃線的差異列表。這些不能被使用?例如,

if (typeof(_.invoke) !== 'undefined'){ 
    // it's lodash 
} 

但是,是的,放大由@費利克斯 - 克林和@tadman等人的意見,如果可能的話,它可能是更可靠的限制問題的功能(如:具體的方法)水平而不是整個圖書館。

+3

'_.invoke'在兩者上都可用。 '_.at'將是一個更好的選擇(僅適用於自V1 lodash) – Jack

+1

我已經添加到了這個問題,以幫助澄清:**加載的下劃線的版本可能會改變(這是一個CMS框架的一部分可能會更新),所以依靠缺少特定功能似乎不可行。** –