Why use typeof for identifying a function?

后端 未结 6 618
天涯浪人
天涯浪人 2020-12-09 13:03

Are there any significant reasons for using

typeof variable === \'function\'

versus

!!variable.call

for d

6条回答
  •  误落风尘
    2020-12-09 13:27

    jQuery's isFunction avoids the RegExp problem you mention by toString-ing the object and checking the result against a map of known types. From the latest source, here's the map:

    // Populate the class2type map
    jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
        class2type[ "[object " + name + "]" ] = name.toLowerCase();
    });
    

    And here's how it's used:

    type: function( obj ) {
        return obj == null ?
            String( obj ) :
            class2type[ toString.call(obj) ] || "object";
    },
    
    // 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).
    isFunction: function( obj ) {
        return jQuery.type(obj) === "function";
    },
    

    You can learn a lot reading the jQuery source.

    • http://james.padolsey.com/jquery/#v=1.5.0&fn=jQuery.isFunction
    • http://james.padolsey.com/jquery/#v=1.5.0&fn=jQuery.type

提交回复
热议问题