修复 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。
那如何完善这个问题呢?
typeof 检测某个方法(例如:document.getElementById) 是否是 object,如何是,则重写 isFunction 函数;
怎样重写呢?正则判断传入的对象字符串后(”" + 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);
};
})()
参考阅读: