您好,登錄后才能下訂單哦!
本篇文章為大家探討JavaScript判斷函數(shù)是否為原生函數(shù)的方法,相信大部分人都還沒學(xué)會這個技能,為了讓大家學(xué)會,給大家總結(jié)了以下內(nèi)容,話不多說,一起往下看吧。
在我的開發(fā)工作中經(jīng)常會遇到需要判斷一個函數(shù)是否是JavaScript原生函數(shù)的情況,有時候這是一個很必要的工作,你需要知道這個函數(shù)是瀏覽器自身提供的,還是由第三方封裝、偽裝成原生函數(shù)。當(dāng)然,最好的方法是考察執(zhí)行這個函數(shù)的toString
方法的返回值。
完成這個任務(wù)的方法非常簡單:
function isNative(fn) { return (/\{\s*\[native code\]\s*\}/).test('' + fn); }
toString
方法會返回這個方法的字符串形式,然后用正則表達(dá)式判斷里面包含的字符。
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ù)雜,但更強(qiáng)大。當(dāng)然,這不是為了做安全防護(hù),它只是給你提供是否是原生函數(shù)的相關(guān)信息。
以上就是JavaScript判斷函數(shù)是否為原生函數(shù)的方法,看完之后是否有所收獲呢?如果想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊,感謝各位的閱讀。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。