检测一个函数是否是JavaScript原生函数的小技巧_javascript技巧
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了检测一个函数是否是JavaScript原生函数的小技巧_javascript技巧,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2028字,纯文字阅读大概需要3分钟。
内容图文
![检测一个函数是否是JavaScript原生函数的小技巧_javascript技巧](/upload/InfoBanner/zyjiaocheng/325/bea8ec0b23ef4d7cb2c6af11cb00bad9.jpg)
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原生函数的小技巧_javascript技巧全部内容,希望文章能够帮你解决检测一个函数是否是JavaScript原生函数的小技巧_javascript技巧所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。