The trend of browsers is to add more and more objects, like Worker, while also adding new methods to old objects. The first step to be compatible with it is to detect whether they exist. If not, add your own compatibility code. The problem comes at this time. Some class libraries do this step for you, but sometimes they don't. Sometimes they do it, but it doesn't meet the standards. Therefore simply typeof Array.prototype.map === "function" may not be enough. At this time the isNative method will appear.
The version I have been using, written by myself:
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
}
But the world is like this Big, I must have studied this problem. The following is Diego Perini’s version, pointing out that Safari’s toString value of the native method is actually unsociable:
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, which can specify the method of the native object. , but one parameter has nothing to do with two parameters. The result just shows that we are still some distance away from perfection. Even if the union of these two functions is taken, it may not be the correct complete set.
Of course this is not a question of [native code] or source code not available or [function], because in JavaScript, it is easy to copy various methods and objects. For example, the following code can successfully fool the detection code.
window.test = {
toString: function( ) {
return '[function]';
}
};
isNative(window, 'test'); // true
Finally I got it from nwmathers Find this:
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, ''));
};
})();