修复 jQuery 中 isFunction 方法的 BUG

作者:怿飞 来源:怿飞blog 时间:2010-01-25 12:05:00 

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 方法等)。

为什么会这样呢?

详细看测试页面:http://www.planabc.net/demo/isfunction/

会发现在 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);
           };
})()

参考阅读:

标签:jquery,isfunction,bug
0
投稿

猜你喜欢

  • Python函数式编程指南(四):生成器详解

    2023-08-23 05:50:02
  • Python对多个sheet表进行整合实例讲解

    2021-01-15 06:18:24
  • python监控进程状态,记录重启时间及进程号的实例

    2022-04-22 07:47:20
  • 如何在SQL Server 2005数据库中导入SQL Server 2008的数据

    2024-01-27 22:05:21
  • Python编程快速上手——strip()函数的正则表达式实现方法分析

    2022-07-24 07:08:59
  • Python matplotlib读取excel数据并用for循环画多个子图subplot操作

    2021-03-28 19:17:31
  • js数组的基本用法及数组根据下标(数值或字符)移除元素

    2024-04-10 10:40:26
  • 在MySQL中为何不建议使用utf8

    2024-01-27 07:07:58
  • 完美的渐变透明效果,支持Firefox

    2008-06-18 18:18:00
  • 面向站长和网站管理员的Web缓存加速指南[翻译]

    2008-04-22 21:04:00
  • MySQL笔记之触发器的应用

    2024-01-18 17:23:32
  • python 日期排序的实例代码

    2023-12-02 16:09:35
  • 两个MySql服务的应用

    2024-01-20 11:02:00
  • JavaScript,5种调用函数的方法[译]

    2009-02-24 16:26:00
  • asp中Access与Sql Server数据库区别总结

    2007-11-18 15:08:00
  • SQL Server跟踪数据实现索引优化向导

    2009-02-13 17:14:00
  • Golang官方限流器库实现限流示例详解

    2024-05-02 16:26:47
  • Django框架 Pagination分页实现代码实例

    2021-08-18 19:32:52
  • 在图片上显示左右箭头类似翻页的代码

    2024-04-19 09:48:20
  • python查找特定名称文件并按序号、文件名分行打印输出的方法

    2023-11-27 03:35:35
  • asp之家 网络编程 m.aspxhome.com