首頁 > web前端 > js教程 > 主體

偵測一個函數是否是JavaScript原生函數的小技巧_javascript技巧

WBOY
發布: 2016-05-16 16:09:57
原創
1029 人瀏覽過

在我的開發工作中經常會遇到需要判斷一個函數是否是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;
}());


現在你也看到了,很複雜,但更強大。當然,這不是為了做安全防護,它只是提供你是否是原生函數的相關資訊。
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!