久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

檢測(cè)一個(gè)函數(shù)是否是JavaScript原生函數(shù)

瀏覽:128日期:2023-11-20 08:04:42

在我的開(kāi)發(fā)工作中經(jīng)常會(huì)遇到需要判斷一個(gè)函數(shù)是否是JavaScript原生函數(shù)的情況,有時(shí)候這是一個(gè)很必要的工作,你需要知道這個(gè)函數(shù)是瀏覽器自身提供的,還是由第三方封裝、偽裝成原生函數(shù)。當(dāng)然,最好的方法是考察執(zhí)行這個(gè)函數(shù)的toString方法的返回值。

The JavaScript

完成這個(gè)任務(wù)的方法非常簡(jiǎn)單:

function isNative(fn) {return (/{s*[native code]s*}/).test(’’ + fn);}

toString方法會(huì)返回這個(gè)方法的字符串形式,然后用正則表達(dá)式判斷里面包含的字符。

更強(qiáng)悍的方法

Lodash的創(chuàng)始人John-David Dalton找到了一個(gè)更佳的方案:

;(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)信息。

標(biāo)簽: JavaScript
相關(guān)文章:
主站蜘蛛池模板: 鄂温| 博野县| 特克斯县| 永登县| 旌德县| 漳平市| 南丹县| 阳谷县| 营口市| 会泽县| 越西县| 长泰县| 山阳县| 渑池县| 花莲市| 灌阳县| 亳州市| 酒泉市| 新巴尔虎左旗| 澄城县| 太原市| 濮阳县| 化州市| 青神县| 汾西县| 壤塘县| 宁强县| 公安县| 沾化县| 徐水县| 武强县| 富蕴县| 潼南县| 广元市| 大余县| 珠海市| 土默特右旗| 阿巴嘎旗| 海原县| 山东省| 鄂温|