SoFunction
Updated on 2025-02-28

In JavaScript, determine whether the function is native code.

I always often 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 isfunction isNative(fn) { 
// Example:// () 
// "function alert() { [native code] }" 
// '' + fn takes advantage of js' implicit type conversion.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 passed parameter value `[[Class]]`var toString = ; 

// Get the original function toString method, used to handle the decompilation code of functionsvar fnToString = ; 

// Used to detect host object constructors,// (Safari > 4; really output specific array, really typed array specific)var reHostCtor = /^\[object .+?Constructor\]$/; 

// Use RegExp to compile the commonly used native methods into regular templates.// Using `Object#toString` is because generally he will not be contaminatedvar reNative = RegExp('^' +// `Object#toString` is forced to stringString(toString)// Escape all regex-related special characters.replace(/[.*+?^${}()|[\]\/\\]/g, '\\$&') 
// To maintain the universality of the template, replace `toString` with `.*?`// Replace characters like `for ...` to be compatible with Rhino and other environments, because they will have additional information, such as the number of parameters of the method..replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') 
// End symbol+ '$' 
); 

function isNative(value) { 
//Judge typeofvar type = typeof value; 
return type == 'function' 
// Use `Function#toString`Native method to call,// instead of value your own `toString` method,// To avoid being deceived by forgery.? ((value)) 
// If type is not 'function',// You need to check the host object,// Because some (browser) environments will treat things like typed arrays as DOM methods// The standard Native regular mode may not be matched at this time: (value && type == 'object' && ((value))) || false; 
}; 

// You can assign isNative to the variable/object you want = isNative; 
}());

Test code:

isNative(isNative) //false 
isNative(alert) //true 
() //false 
() //true 
() //true