JavaScript determines if the native function checks if the function is native code

  • 2020-03-30 03:56:48
  • OfStack

JavaScript code

Determining whether a function is a native method is fairly simple:


//Determine if the function is native
function isNative(fn) { 
//Example:
// alert.toString() 
// "function alert() { [native code] }" 
//'' + fn takes advantage of js's implicit typecasting.
return (/{s*[native code]s*}/).test('' + fn); 
}

Converting a function to a string representation and performing regular matching is how this works.

Updated version, Update!


;(function() { 

//Gets the toString method of Object to handle the internal '[[Class]]' of the passed parameter value
var toString = Object.prototype.toString; 

//Gets the original toString method of Function to handle the decompilation of functions
var fnToString = Function.prototype.toString; 

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

//Use RegExp to compile common native methods into regular templates.
//'Object#toString' is used because it is not normally contaminated
var reNative = RegExp('^' + 
//'Object#toString' is strong to a string
String(toString) 
//Escapes all special characters associated with regular expressions
.replace(/[.*+?^${}()|[]/\]/g, '\$&') 
//To keep the template generic, replace 'toString' with '.*? `
//Will ` for... Character substitutions such as' are compatible with Rhino and other environments because they have additional information, such as the number of arguments to a method.
.replace(/toString|(function).*?(?=\()| for .+?(?=\])/g, '$1.*?') 
//terminator
+ '$' 
); 

function isNative(value) { 
//Judge the typeof
var type = typeof value; 
return type == 'function' 
//Function#toString 'native method to call,
//Instead of value's own 'toString' method,
//To avoid being deceived by forgeries.
? reNative.test(fnToString.call(value)) 
//If type is not 'function',
//Then you need to check the case of the host object,
//Because some (browser) environments treat things like typed arrays as DOM methods
//The standard Native regular pattern may not match at this point
: (value && type == 'object' && reHostCtor.test(toString.call(value))) || false; 
}; 

//IsNative can be assigned to any variable/object you want
window.isNative = isNative; 
}());

Test code:


isNative(isNative) //false 
isNative(alert) //true 
window.isNative(window.isNative) //false 
window.isNative(window.alert) //true 
window.isNative(String.toString) //true

Related articles: