(typeof variable === “function”) 和 jQuery.isFunction() 有什么区别

What's the difference between (typeof variable === "function") and jQuery.isFunction()?

本文关键字:isFunction 什么 jQuery 区别 typeof variable function      更新时间:2023-09-26

我一直使用(typeof variable === "function"),我偶然发现了jQuery.isFunction(),我想知道:

  1. typeof 方法和 jQuery 的方法有什么区别?不仅有什么区别,而且
  2. 什么时候适合使用 typeof 方法,什么时候适合使用 jQuery 的方法?
几乎没有

区别,除了使用jQuery稍微慢一点。请参阅源代码:

isFunction: function( obj ) {
    return jQuery.type(obj) === "function";
},

它调用一个函数,该函数调用另一个函数来确定与您:P显示的内容完全相同的内容

在这种情况下,jQuery实际上没有任何优势[或者对于这种方式,库的90%用例]。查看Vanilla-JS并查看其:P的一些功能

TLDR:不要为此使用 jQuery...什么的。

更新

这里有一个基准测试,显示Vanilla JS比jQuery快大约93%:http://jsperf.com/jquery-isfunction-vs-vanilla-is-function。

没有区别。jQuery使用相同的概念:

// ...
isFunction: function( obj ) {
    return jQuery.type(obj) === "function";
}

更新:

深入挖掘后,我发现jQuery的isFunction方法是将function() {}Object.prototype链的toString方法与字符串[object Function]进行比较。这就是它与您之前的示例的不同之处,也是它比 typeof 慢的原因。

isFunction 的 jQuery 源代码是

isFunction: function( obj ) {
    return jQuery.type(obj) === "function";
},
type: function( obj ) {
return obj == null ?
   String( obj ) :
   class2type[ core_toString.call(obj) ] || "object";
},
//...
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "),
   function(i, name) {
      class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
core_toString = Object.prototype.toString,

因此,当且仅当在其参数上调用 Object.prototype.toString.call 返回 [object Function] 时,jQuery.isFunction返回 true。

通常你可以通过这个测试来测试JS对象是否是函数:

(typeof fn === 'function')

但是,这并不总是有效 (IE8(:

typeof alert => 'object'
typeof document.createElement('input').getAttribute => 'object'

在jQuery 1.4之前,他们在内部使用相同的检查,但现在他们已经修复了它。因此,为了确保传递的对象是可以调用的函数,只需使用 $.isFunction 方法:

$.isFunction(function() {}) => true
$.isFunction(alert) => true
$.isFunction(document.createElement('input').getAttribute) => true

复制自此博客: http://nuald.blogspot.co.uk/2012/07/why-jqueryisfunction.html

不同之处在于 JQuery 调用等效于以下内容的内容并检查"函数"字符串标记:

var toString = Object.prototype.toString;
var func = function(){};
console.log(toString.call(func)); // "returns [object Function]"

而 typof,只返回 "function":

var fType = typeof func; 
console.log(fType); // returns "function"

下面是一个示例。