欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

jQuery中isFunction方法的BUG修復

 更新時間:2010年01月25日 20:21:28   作者:  
修復 jQuery 中 isFunction 方法的 BUG

jQuery 1.4 源碼 449 行(core.js 431 行),判斷是否為函數(shù)的方法如下(思路來源于 Douglas Crockford 的《The Miller Device》):

isFunction: function( obj ) {
   
return toString.call(obj) === "[object Function]";
},

同時 jQuery 的作者也作了部分注釋:

See test/unit/core.js for details concerning isFunction. Since version 1.3, DOM methods and functions like alert aren't supported. They return false on IE (#2968).

即:此方法在 IE 下無法正確識別 DOM 方法和一些函數(shù)(例如 alert 方法等)。

為什么會這樣呢?


[Ctrl+A 全選 注:引入外部Js需再刷新一下頁面才能執(zhí)行]

會發(fā)現(xiàn)在 IE 下用 typeof 檢測 alert、confirm 方法以及 DOM 的方法顯示 object,而其他瀏覽器下顯示 function。

那如何完善這個問題呢?

  1. typeof 檢測某個方法(例如:document.getElementById) 是否是 object,如何是,則重寫 isFunction 函數(shù);
  2. 怎樣重寫呢?正則判斷傳入的對象字符串后(”" + fn),是否起始位置含有 function,即:/^\s*\bfunction\b/.test(” + fn)。

OK,看下根據(jù)以上思路修改后的 isFunction 函數(shù):

復制代碼 代碼如下:

var isFunction = (function() { // Performance optimization: Lazy Function Definition return "object" === typeof document.getElementById ? isFunction = function(fn){ try { return /^\s*\bfunction\b/.test("" + fn); } catch (x) { return false } }: isFunction = function(fn){ return "[object Function]" === Object.prototype.toString.call(fn); };})()

參考閱讀:

相關文章

最新評論