温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScript判断函数是否为原生函数的方法

发布时间:2020-06-19 11:08:25 来源:亿速云 阅读:156 作者:Leah 栏目:web开发

本篇文章为大家探讨JavaScript判断函数是否为原生函数的方法,相信大部分人都还没学会这个技能,为了让大家学会,给大家总结了以下内容,话不多说,一起往下看吧。

在我的开发工作中经常会遇到需要判断一个函数是否是JavaScript原生函数的情况,有时候这是一个很必要的工作,你需要知道这个函数是浏览器自身提供的,还是由第三方封装、伪装成原生函数。当然,最好的方法是考察执行这个函数的toString方法的返回值。

The JavaScript

完成这个任务的方法非常简单:

function isNative(fn) {
	return (/\{\s*\[native code\]\s*\}/).test('' + fn);
}

toString方法会返回这个方法的字符串形式,然后用正则表达式判断里面包含的字符。

更强悍的方法

Lodash的创始人John-David Dalton找到了一个更佳的方案:

;(function() {

  // Used to resolve the internal `[[Class]]` of values
  var toString = Object.prototype.toString;
  
  // Used to resolve the decompiled source of functions
  var fnToString = Function.prototype.toString;
  
  // Used to detect host constructors (Safari > 4; really typed array specific)
  var reHostCtor = /^\[object .+?Constructor\]$/;

  // Compile a regexp using a common native method as a template.
  // We chose `Object#toString` because there's a good chance it is not being mucked with.
  var reNative = RegExp('^' +
    // Coerce `Object#toString` to a string
    String(toString)
    // Escape any special regexp characters
    .replace(/[.*+?^${}()|[\]\/\\]/g, '\\$&')
    // Replace mentions of `toString` with `.*?` to keep the template generic.
    // Replace thing like `for ...` to support environments like Rhino which add extra info
    // such as method arity.
    .replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  );
  
  function isNative(value) {
    var type = typeof value;
    return type == 'function'
      // Use `Function#toString` to bypass the value's own `toString` method
      // and avoid being faked out.
      ? reNative.test(fnToString.call(value))
      // Fallback to a host object check because some environments will represent
      // things like typed arrays as DOM methods which may not conform to the
      // normal native pattern.
      : (value && type == 'object' && reHostCtor.test(toString.call(value))) || false;
  }
  
  // export however you want
  module.exports = isNative;
}());

现在你也看到了,很复杂,但更强大。当然,这不是为了做安全防护,它只是给你提供是否是原生函数的相关信息。

以上就是JavaScript判断函数是否为原生函数的方法,看完之后是否有所收获呢?如果想了解更多相关内容,欢迎关注亿速云行业资讯,感谢各位的阅读。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI