JavaScript小技巧:如何检测一个函数是否是JavaScript原生函数
来源:互联网 发布:黑龙江11选五遗漏数据 编辑:程序博客网 时间:2024/06/06 17:17
在我的开发工作中经常会遇到需要判断一个函数是否是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;}());
现在你也看到了,很复杂,但更强大。当然,这不是为了做安全防护,它只是给你提供是否是原生函数的相关信息。
0 0
- JavaScript小技巧:如何检测一个函数是否是JavaScript原生函数
- javascript 判断一个函数是否是generator
- JavaScript中如何检测一个变量是一个String类型?请写出函数实现
- 如何判断是否是原生js函数
- javascript安全类型检测(判断是否是原生对象)
- javascript常用原生函数
- JavaScript几种原生函数
- 原生如何检测变量是否是一个数组的几种方法
- javascript常用函数+技巧
- Javascript--函数技巧
- JavaScript函数写法技巧
- 常用Javascript检测函数:检测对像,函数,ID是否存在
- JavaScript函数小集锦
- JavaScript函数小集锦
- javascript函数小集锦
- JavaScript函数小集锦
- JavaScript函数小集锦
- JavaScript函数小集锦
- IE8兼容IE7
- tomcat下server.xml中context介绍
- 十六进制字符串与数值类型之间转换
- Java enum 枚举还可以这么用
- hdu4295 4 substrings problem 状压dp
- JavaScript小技巧:如何检测一个函数是否是JavaScript原生函数
- C++ 学习笔记_0009_枚举(谁是小偷、都要学C、污损的数字)
- ASP.NET中JSON的序列化和反序列化
- Cocos2d-x 配置Android & cocos2d-x 开发环境
- 关于django中修改js css文件但浏览器无法及时与之改变的问题
- hdu4044 GeoDefense 树形dp
- Android消息处理机制
- 【Leetcode】Divide Two Integers
- 清澄 1000 1001 1002