1024programmer Java JS determines whether it is a native method_javascript skills

JS determines whether it is a native method_javascript skills

The trend in browsers is to add more and more objects, like Workers, while also adding new methods to old objects. The first step in how 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 is written by 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

But the world is so big, there must be people who 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:

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 and two parameters have nothing to do with each other. The result just shows that we are still some distance 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.

The code is as follows:

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

isNative(window, test); // true
Finally I found this from 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, ));

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/633039

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us


Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top