Home >Web Front-end >JS Tutorial >JS determines whether it is a native method_javascript skills

JS determines whether it is a native method_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:28:021211browse

The trend in browsers is to add more and more objects, like Workers, 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:

Copy the code 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
}

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:
Copy code 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, which can specify the method of the native object, but One parameter or two parameters doesn't matter. 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.
Copy code The code is as follows:

window.test = {
toString: function( ) {
return [function];
}
};

isNative(window, test); // true
Finally I found this from nwmathers:
Copy code 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, ));
};
})();
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn