设为首页 - 加入收藏
广告 1000x90
您的当前位置:主页 > 教程 > 网页设计 > 正文

JavaScript小技巧:如何检测一个函数是否是JavaScript原生函数

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

The JavaScript
完成这个任务的方法非常简单
  1. function isNative(fn) { 
  2.     return (/\{\s*\[native code\]\s*\}/).test('' + fn); 

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

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

  1. ;(function() { 
  2.  
  3.   // Used to resolve the internal `[[Class]]` of values 
  4.   var toString = Object.prototype.toString; 
  5.    
  6.   // Used to resolve the decompiled source of functions 
  7.   var fnToString = Function.prototype.toString; 
  8.    
  9.   // Used to detect host constructors (Safari > 4; really typed array specific) 
  10.   var reHostCtor = /^\[object .+?Constructor\]$/; 
  11.  
  12.   // Compile a regexp using a common native method as a template. 
  13.   // We chose `Object#toString` because there's a good chance it is not being mucked with. 
  14.   var reNative = RegExp('^' + 
  15.     // Coerce `Object#toString` to a string 
  16.     String(toString) 
  17.     // Escape any special regexp characters 
  18.     .replace(/[.*+?^${}()|[\]\/\\]/g, '\\$&'
  19.     // Replace mentions of `toString` with `.*?` to keep the template generic. 
  20.     // Replace thing like `for ...` to support environments like Rhino which add extra info 
  21.     // such as method arity. 
  22.     .replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' 
  23.   ); 
  24.    
  25.   function isNative(value) { 
  26.     var type = typeof value; 
  27.     return type == 'function' 
  28.       // Use `Function#toString` to bypass the value's own `toString` method 
  29.       // and avoid being faked out. 
  30.       ? reNative.test(fnToString.call(value)) 
  31.       // Fallback to a host object check because some environments will represent 
  32.       // things like typed arrays as DOM methods which may not conform to the 
  33.       // normal native pattern. 
  34.       : (value && type == 'object' && reHostCtor.test(toString.call(value))) || false
  35.   } 
  36.    
  37.   // export however you want 
  38.   module.exports = isNative; 
  39. }()); 

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

相关推荐:

网友评论:

发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
Copyright © 2021 众联设计之家

Power by DedeCms

Top