Check whether a function is a native code, the simplest way is, of course, to determine the value returned by the toString method of a function, I often encounter the need to check whether a function is a native code-this is a very important part of function Testing: functions are supported by browsers or simulated by third-party class libraries. To detect this, the simplest way is to determine the value returned by the toString method of the function.
JavaScript code
Determining whether a function is a native method is actually quite simple:
// Determine whether the native function isNative (fn) {// example: // alert. toString () // "function alert () {[native code]}" // ''+ fn uses the implicit type conversion of js. return (/\ {\ s * \ [native code \] \ s *\}/). test (''+ fn );}
Converts a function to a string representation and performs regular matching. This is the principle of implementation.
Upgrade, Update!
; (Function () {// obtain the Object's toString method, used to process the internal (internal) '[[Class] 'var toString = Object. prototype. toString; // The toString method for obtaining the original Function. It is used to process the decompilation code var fnToString = Function of functions. prototype. toString; // used to detect host constructors, // (Safari> 4; returns a specific array, really typed array specific) var reHostCtor =/^ \ [object. +? Constructor \] $/; // use RegExp to compile common native methods into regular templates. // use 'object # tostring' because it is generally not contaminated var reNative = RegExp ('^' + // convert 'object # tostring' to a String (toString) // escape all special characters related to regular expressions. replace (/[. * +? ^ $ {} () | [\] \/\]/G, '\ $ &') // to ensure the versatility of the template, replace 'tostring' '. *? '// Set'... 'and other characters, compatible with environments such as Rhino, because they have additional information, such as the number of parameters of the method .. replace (/toString | (function ). *? (? ==\\ () | For. +? (? =\\])/G, '$1 .*? ') // Terminator +' $ '); function isNative (value) {// judge typeof var type = typeof value; return type = 'function' // use the 'function # tostring' native method to call the function. // instead of the value's own 'tostring' method, // avoid spoofing .? ReNative. test (fnToString. call (value) // if the type is not 'function', // you need to check the situation of the host object. // some (browsers) the environment treats things such as typed arrays as DOM Methods // This may not match the standard Native regular mode: (value & type = 'object' & reHostCtor. test (toString. call (value) | false ;}; // assign isNative to the expected variable/Object window. isNative = isNative ;}());
isNative(isNative) //false isNative(alert) //true window.isNative(window.isNative) //false window.isNative(window.alert) //true window.isNative(String.toString) //true