檢測一個函數(shù)是否是JavaScript原生函數(shù)的小技巧
在我的開發(fā)工作中經(jīng)常會遇到需要判斷一個函數(shù)是否是JavaScript原生函數(shù)的情況,有時候這是一個很必要的工作,你需要知道這個函數(shù)是瀏覽器自身提供的,還是由第三方封裝、偽裝成原生函數(shù)。當然,最好的方法是考察執(zhí)行這個函數(shù)的toString方法的返回值。
The JavaScript
完成這個任務(wù)的方法非常簡單:
function isNative(fn) {
return (/\{\s*\[native code\]\s*\}/).test('' + fn);
}
toString方法會返回這個方法的字符串形式,然后用正則表達式判斷里面包含的字符。
更強悍的方法
Lodash的創(chuàng)始人John-David Dalton找到了一個更佳的方案:
;(function() {
// Used to resolve the internal `[[Class]]` of values
var toString = Object.prototype.toString;
// Used to resolve the decompiled source of functions
var fnToString = Function.prototype.toString;
// Used to detect host constructors (Safari > 4; really typed array specific)
var reHostCtor = /^\[object .+?Constructor\]$/;
// Compile a regexp using a common native method as a template.
// We chose `Object#toString` because there's a good chance it is not being mucked with.
var reNative = RegExp('^' +
// Coerce `Object#toString` to a string
String(toString)
// Escape any special regexp characters
.replace(/[.*+?^${}()|[\]\/\\]/g, '\\$&')
// Replace mentions of `toString` with `.*?` to keep the template generic.
// Replace thing like `for ...` to support environments like Rhino which add extra info
// such as method arity.
.replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
function isNative(value) {
var type = typeof value;
return type == 'function'
// Use `Function#toString` to bypass the value's own `toString` method
// and avoid being faked out.
? reNative.test(fnToString.call(value))
// Fallback to a host object check because some environments will represent
// things like typed arrays as DOM methods which may not conform to the
// normal native pattern.
: (value && type == 'object' && reHostCtor.test(toString.call(value))) || false;
}
// export however you want
module.exports = isNative;
}());
現(xiàn)在你也看到了,很復(fù)雜,但更強大。當然,這不是為了做安全防護,它只是給你提供是否是原生函數(shù)的相關(guān)信息。
- JavaScript判斷頁面加載完之后再執(zhí)行預(yù)定函數(shù)的技巧
- JavaScript中split與join函數(shù)的進階使用技巧
- 個人總結(jié)的一些JavaScript技巧、實用函數(shù)、簡潔方法、編程細節(jié)
- JavaScript中的alert()函數(shù)使用技巧詳解
- Powershell小技巧之使用Jint引擎在PowerShell中執(zhí)行Javascript函數(shù)
- Javascript中產(chǎn)生固定結(jié)果的函數(shù)優(yōu)化技巧
- js中字符替換函數(shù)String.replace()使用技巧
- js函數(shù)使用技巧之 setTimeout(function(){},0)
- js 格式化時間日期函數(shù)小結(jié)
- javascript函數(shù)中的3個高級技巧
相關(guān)文章
javascript實現(xiàn)在網(wǎng)頁任意處點左鍵彈出隱藏菜單的方法
這篇文章主要介紹了javascript實現(xiàn)在網(wǎng)頁任意處點左鍵彈出隱藏菜單的方法,設(shè)計鼠標事件及css樣式操作的相關(guān)技巧,需要的朋友可以參考下2015-05-05全面了解構(gòu)造函數(shù)繼承關(guān)鍵apply call
下面小編就為大家?guī)硪黄媪私鈽?gòu)造函數(shù)繼承關(guān)鍵apply call。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-07-07js使用xml數(shù)據(jù)載體實現(xiàn)城市省份二級聯(lián)動效果
這篇文章主要為大家詳細介紹了js使用xml數(shù)據(jù)載體實現(xiàn)城市省份二級聯(lián)動效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11