检测一个函数是否是JavaScript原生函数的小技巧_javascript技巧
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;
}());
现在你也看到了,很复杂,但更强大。当然,这不是为了做安全防护,它只是给你提供是否是原生函数的相关信息。
推荐阅读
-
一个可以随意添加多个序列的tag函数_javascript技巧
-
按下回车键指向下一个位置的一个函数代码_javascript技巧
-
用js判断输入是否为中文的函数_javascript技巧
-
检测一个函数是否是JavaScript原生函数
-
js 事件处理函数间的Event物件是否全等_javascript技巧
-
JavaScript检查某个function是否是原生代码的方法_javascript技巧
-
javascript检测页面是否缩放的小例子_javascript技巧
-
使一个函数作为另外一个函数的参数来运行的javascript代码_javascript技巧
-
js 事件处理函数间的Event物件是否全等_javascript技巧
-
JavaScript检查某个function是否是原生代码的方法_javascript技巧