国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

檢測一個函數(shù)是否是JavaScript原生函數(shù)的小技巧

2019-11-20 12:57:25
字體:
供稿:網(wǎng)友

在我的開發(fā)工作中經(jīng)常會遇到需要判斷一個函數(shù)是否是JavaScript原生函數(shù)的情況,有時候這是一個很必要的工作,你需要知道這個函數(shù)是瀏覽器自身提供的,還是由第三方封裝、偽裝成原生函數(shù)。當然,最好的方法是考察執(zhí)行這個函數(shù)的toString方法的返回值。

The JavaScript

完成這個任務的方法非常簡單:

復制代碼 代碼如下:

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

toString方法會返回這個方法的字符串形式,然后用正則表達式判斷里面包含的字符。

更強悍的方法

Lodash的創(chuàng)始人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;
}());


現(xiàn)在你也看到了,很復雜,但更強大。當然,這不是為了做安全防護,它只是給你提供是否是原生函數(shù)的相關(guān)信息。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 鞍山市| 东乡族自治县| 福州市| 尉犁县| 长岭县| 乐清市| 昆明市| 长春市| 会东县| 乌苏市| 方山县| 芜湖县| 临颍县| 涪陵区| 军事| 府谷县| 满洲里市| 尚义县| 阿克苏市| 宜州市| 蚌埠市| 改则县| 上高县| 洛扎县| 凭祥市| 陆川县| 克什克腾旗| 翁源县| 泾源县| 禄劝| 肥乡县| 正定县| 若尔盖县| 盐源县| 新疆| 海宁市| 安阳市| 刚察县| 平谷区| 昆山市| 万年县|