当前位置: 首页 > 图文教程 > 网络编程 > Javascript > jQuery中isFunction方法的BUG修复

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 jQuery中isFunction方法的BUG修复


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-02-27   浏览: 334 ::
收藏到网摘: n/a

修复 jQuery 中 isFunction 方法的 BUG

jQuery 1.4 源码 449 行(core.js 431 行),判断是否为函数的方法如下(思路来源于 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 方法和一些函数(例如 alert 方法等)。

为什么会这样呢?


[Ctrl+A 全选 提示:你可先修改部分代码,再按运行]

会发现在 IE 下用 typeof 检测 alert、confirm 方法以及 DOM 的方法显示 object,而其他浏览器下显示 function。

那如何完善这个问题呢?

  1. typeof 检测某个方法(例如:document.getElementById) 是否是 object,如何是,则重写 isFunction 函数;
  2. 怎样重写呢?正则判断传入的对象字符串后(”" + fn),是否起始位置含有 function,即:/^\s*\bfunction\b/.test(” + fn)。

OK,看下根据以上思路修改后的 isFunction 函数:

复制代码 代码如下:

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); };})()

参考阅读: