The trend of browsers is to add more and more objects, like worker, while adding new methods for old objects. The first step in how to be compatible with it is to detect whether they exist or not to patch up their compatible code. Then the problem comes, some class library is for you to do this step, but sometimes not, sometimes is done, but does not conform to the standard. So pure is typeof Array.prototype.map = = "function" may not be enough. Then the Isnative method is coming.
I have been using the version of myself to write:
Copy Code code as follows:
var isnative = function (method) {///Determine whether it is native
Return!! Method && (/\{\s*\[native code\]\s*\}/.test (method+ "") | |
/\{\s*\/\* source code not available \*\/\s*\}/.test (method+ ""));//This is to be compatible with opera9.x.
}
But the world is so big, certainly has studied this question, the following is Diego Perini version, pointed out safari to native method's ToString value actually also is a loner:
Copy Code code as follows:
var isnative = function (object, method) {
Return object && method in Object &&
typeof Object[method]!= ' string ' &&
IE & Consortium Browser return "[native code]"
Safari < = 2.0.4 'll return "[function]"
(/\{\s*\[native code\]\s*\}|^\[function\]$/). Test (Object[method]);
}
It has one more argument than my version, and can specify the method of the native object, but a parameter is not related to two parameters, and the result just shows that we are still a little far from perfect. Even if these two functions are set together, they may not be the correct collection.
Of course this is not [native code] or source code not available or [function] problem, because to JavaScript, it is easy to cottage various methods and objects. For example, the following code can successfully cheat the detection code.
Copy Code code as follows:
Window.test = {
Tostring:function () {
Return ' [function] ';
}
};
isnative (window, ' test '); True
Finally, I found this from nwmathers:
Copy Code code 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, '));
};
})();