I always encounter situations where I need to check whether a function is native code - this is a very important content in functional testing: is the function supported by the browser built-in or simulated through third-party class libraries. To detect this, the easiest way is of course to judge the value returned by the toString method of the function.
JavaScript Code
It is actually quite simple to determine whether a function is native:
// Determine whether the native function function isNative(fn) { // Example: // alert.toString() // "function alert() { [native code] }" // '' + fn utilizes the implicit type conversion of js. return (//{/s*/[native code/]/s*/}/).test('' + fn); }Convert the function into a string representation and perform regular matching, this is the principle of implementation.
Upgraded version, Update!
;(function() { // Get the toString method of Object, used to process the internal (internal) of the value passed in parameter `[[Class]]` var toString = Object.prototype.toString; // Get the toString method of primitive Function, used to handle the decompilation code of functions var fnToString = Function.prototype.toString; // Used to detect host object constructors (host constructors), // (Safari > 4; Really output specific array specific) var reHostCtor = /^/[object .+?Constructor/]$/; // Use RegExp to compile the commonly used native methods into regular templates. // Use `Object#toString` because it is generally not polluted var reNative = RegExp('^' + // Force `Object#toString` to string String(toString) // Escape all special characters related to regular expressions. replace(/[.*+?^${}()|[/]////]/g, '//$&') // To maintain the universality of the template, replace `toString` with `.*?` // Replace characters like `for ...` to be compatible with environments such as Rhino, because they will have additional information, such as the number of parameters of the method. .replace(/toString|(function).*?(?=///()| for .+?(?=///])/g, '$1.*?') // Endword + '$' ); function isNative(value) { // Judge type of typeof var type = typeof value; return type == 'function' // Use the `Function#toString` native method to call, // instead of value your own `toString` method, // to avoid being deceived by forgery. ? reNative.test(fnToString.call(value)) // If type is not 'function', // You need to check the host object(host object), // Because some (browser) environments will treat typed arrays as DOM methods// At this time, the standard Native regular pattern may not be matched: (value && type == 'object' && reHostCtor.test(toString.call(value))) || false; }; // You can assign isNative to the variable/object you want window.isNative = isNative; }());isNative(isNative) //false isNative(alert) //true window.isNative(window.isNative) //false window.isNative(window.alert) //true window.isNative(String.toString) //true