JQuery 1.4 source code line 449 (line 431 of core. js), The method for determining whether it is a function is as follows (The idea comes from The Miller Device of Douglas Crockford):
isFunction: function( obj ) {
return toString.call(obj) === "[object Function]";
},
At the same time, the author of jQuery also made some comments:
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 ).
That is, This method cannot correctly recognize DOM methods and some functions (such as alert methods) in IE ).
Why?
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <ptml xmlns = "http://www.w3.org/1999/xhtml"> <pead> <meta http-equiv =" content-Type "content =" text/html; charset = gb2312 "/> <title> fixed the BUG of the isFunction method in jQuery </title> </pead> <body> used the typeof operator to detect various methods: test the original isFunction method. Test the repaired isFunction method. </body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
You will find that in IE, the typeof method is used to detect alert, confirm, and DOM to display the object, while in other browsers, the function is displayed.
How can we solve this problem?
- Typeof checks whether a method (such as document. getElementById) is an object. If so, rewrite the isFunction;
- How to rewrite it? After the regular expression is used to determine whether the input object string ("" + fn) contains a function at the starting position, that is,/^ \ s * \ bfunction \ B/. test ("+ fn ).
OK. Let's take a look at the modified isFunction:
Copy codeThe Code is as follows:
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 );};})()
Refer:
- IsFunction hacked, isCallable solution
- IsFunction () or isObject (), that is the question? "
- Lazy Function Definition Pattern