This article mainly introduces tips for checking whether a function is a JavaScript Native function. This article provides two detection methods, for more information about how to determine whether a function is a JavaScript Native function, you need to know whether the function is provided by the browser or encapsulated by a third party and disguised as a native function. Of course, the best way is to evaluate the return value of the toString method that executes this function.
The JavaScript
The method for completing this task is very simple:
The code is as follows:
Function isNative (fn ){
Return (/\ {\ s * \ [native code \] \ s * \}/). test (''+ fn );
}
The toString method returns the string form of this method, and then uses a regular expression to determine the characters contained in it.
More powerful method
John David Dalton, founder of Lodash, found a better solution:
The code is as follows:
; (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.
Var reNative = RegExp ('^' +
// Coerce 'object # tostring' to a string
String (toString)
// Escape any special regexp characters
. Replace (/[. * +? ^ $ {} () | [\] \/\]/G, '\ $ &')
// Replace mentions of 'tostring' '.*? '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
// Normal native pattern.
: (Value & type = 'object' & reHostCtor. test (toString. call (value) | false;
}
// Export however you want
Module. exports = isNative;
}());
Now you can see that it is complicated, but more powerful. Of course, this is not for security protection. it just provides you with information about whether it is a native function.