This article introduces js to determine whether to use native methods. If you have any need, you can refer to the browser's trend of adding more and more objects, such as Worker, and adding new methods for old objects. The first step in how to be compatible with it is to check whether they exist or not. If not, add your own compatible code. Then the problem arises. Some class libraries do this for you, but sometimes they do not. Sometimes they do, but they do not conform to the standard. Therefore, typeof Array. prototype. map = "function" may not be enough. The isNative method is coming soon.
The version I have been using. I wrote it myself:
The Code is as follows:
Var isNative = function (method) {// determine whether it is a native method
Return !! Method & (/{s * [native code] s *}/. test (method + "") |
/{S */* source code not available */s *}/. test (method + ""); // This is for compatibility with opera9.x
}
However, if the world is so big, you must have studied this problem. The following is the version of Diego Perini. It is pointed out that safari's toString value for native methods is actually a grouping:
The Code is as follows:
Var isNative = function (object, method ){
Return object & method in object &&
Typeof object [method]! = String &&
// IE & W3C browser return "[native code]"
// Safari <= 2.0.4 will return "[function]"
(/{S * [native code] s *} | ^ [function] $/). test (object [method]);
}
It has one more parameter than my version and can specify the method of the native object, but one parameter has nothing to do with the two parameters. The result only shows that we are still out of perfection. Even if the two functions take the Union set, the complete set may not be correct.
Of course, this is not a problem with [native code], source code not available or [function], because it is easy to copy various methods and objects in javascript. For example, the following code can successfully cheat the detection code.
The Code is as follows:
Window. test = {
ToString: function (){
Return [function];
}
};
IsNative (window, test); // true
Finally, I found this in nwmathers:
The Code is as follows:
Var isNative = (function (){
Var s = (window. open +). replace (/open/g ,);
Return function (object, method ){
Var m = object? Object [method]: false, r = new RegExp (method, g );
Return !! (M & typeof m! = String & s ==( m +). replace (r ,));
};
})();