国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

檢測一個函數是否是JavaScript原生函數

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

在我的開發工作中經常會遇到需要判斷一個函數是否是JavaScript原生函數的情況,有時候這是一個很必要的工作,你需要知道這個函數是瀏覽器自身提供的,還是由第三方封裝、偽裝成原生函數。當然,最好的方法是考察執行這個函數的toString方法的返回值。

The JavaScript

完成這個任務的方法非常簡單:

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

toString方法會返回這個方法的字符串形式,然后用正則表達式判斷里面包含的字符。

更強悍的方法

Lodash的創始人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;}());

現在你也看到了,很復雜,但更強大。當然,這不是為了做安全防護,它只是給你提供是否是原生函數的相關信息。

標簽: JavaScript
相關文章:
主站蜘蛛池模板: 伊宁县| 贞丰县| 象州县| 红安县| 思南县| 马鞍山市| 沛县| 寻乌县| 淅川县| 原阳县| 贵溪市| 厦门市| 离岛区| 汕尾市| 荥阳市| 墨江| 梁山县| 汪清县| 西乡县| 孟津县| 康定县| 阜平县| 于都县| 鹿邑县| 岳阳县| 万载县| 五华县| 眉山市| 呈贡县| 剑河县| 石棉县| 西林县| 南溪县| 如东县| 沙湾县| 和林格尔县| 京山县| 建水县| 弋阳县| 若尔盖县| 阜南县|