I always encounter situations where it is necessary to check whether a function is native--a very important part of the functional test: The function is supported by the browser, or is modeled by a Third-party class library. The easiest way to detect this is, of course, to judge the value returned by the ToString method of the function.
JavaScript code
It is quite simple to judge whether a function is a native method:
To determine if the native function functions
isnative (FN) {
//Example:
//Alert.tostring ()
//"function alert () {[native code]}"
//' + FN utilizes the implicit type conversion of JS.
Return (/\{\s*\[native code\]\s*\}/). Test (' + fn);
}
The principle of implementation is to convert a function to a string representation and perform a regular match.
Upgraded version, update!
;(function () {//Get the ToString method of Object to process the internal (internal) ' [[Class]] ' var toString = Object.prototype.toString of the passed-in parameter value;
Gets the original Function of the ToString method, which is used to process functions code var fntostring = Function.prototype.toString; Used to detect host Object Builder (host constructors),//(Safari > 4; True output specific array, really typed array specific) var rehostctor =/^\[objec T. +?
constructor\]$/;
Use RegExp to compile a common native method into a regular template. Use ' object#tostring ' because generally he will not be contaminated var renative = RegExp (' ^ ' +//convert ' object#tostring ' strong to String (toString)//To all positive The special characters associated with the expression are escaped. Replace (/[.*+?^${} () |[
\]\/\\]/g, ' \\$& ')//To preserve the versatility of the template, replace ' toString ' with '. *? '//To replace characters such as ' for ... ', compatible with rhino and other environments, as they will 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 ' function#tostring ' native method to invoke,//instead of value's own ' toString ' method,///Lest it be deceived by forgery. ? Renative.test (Fntostring.call (value))//if type does notis a ' function ',//You need to check the situation of the host object (s),//Because some (browser) environment will use something like typed arrays as a DOM method//It may not match the standard native regular mode at this point: (Value && type = = ' object ' && rehostctor.test (Tostring.call (value)) | |
False
};
You can assign isnative to the 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